SlideShare uma empresa Scribd logo
1 de 49
Baixar para ler offline
WordPress Queries
           -the right way




                   Anthony Hortin
#wpmelb          @maddisondesigns
How you’re probably querying


query_posts()
get_posts()
new WP_Query()
You’re doing it wrong!
The Loop

if ( have_posts() ) :

 while ( have_posts() ) :

   the_post();

 endwhile;

endif;
The Loop

if ( have_posts() )
 // Determines if there’s anything to iterate
 while ( have_posts() ) :

   the_post();

 endwhile;

endif;
The Loop

if ( have_posts() )

 while ( have_posts() ) :
   // Sets up globals & continues iteration
   the_post();

 endwhile;

endif;
Anatomy of a WordPress Page

The Main Query
wp-blog-header.php
// Loads the WordPress bootstrap
// ie. Sets the ABSPATH constant.
// Loads the wp-config.php file etc.
require_once( dirname(__FILE__) . '/wp-load.php' );


wp();
// Decide which template files to load
// ie. archive.php, index.php etc
require_once( ABSPATH . WPINC . '/template-loader.php' );
wp-blog-header.php
// Loads the WordPress bootstrap
// ie. Sets the ABSPATH constant.
// Loads the wp-config.php file etc.
require_once( dirname(__FILE__) . '/wp-load.php' );


wp();
// Decide which template files to load
// ie. archive.php, index.php etc
require_once( ABSPATH . WPINC . '/template-loader.php' );
wp-blog-header.php
// Loads the WordPress bootstrap
// ie. Sets the ABSPATH constant.
// Loads the wp-config.php file etc.
require_once( dirname(__FILE__) . '/wp-load.php' );


wp();
// Decide which template files to load
// ie. archive.php, index.php etc
require_once( ABSPATH . WPINC . '/template-loader.php' );
wp-blog-header.php
// Loads the WordPress bootstrap
// ie. Sets the ABSPATH constant.
// Loads the wp-config.php file etc.
require_once( dirname(__FILE__) . '/wp-load.php' );

// Does ALL THE THINGS!
wp();
// Decide which template files to load
// ie. archive.php, index.php etc
require_once( ABSPATH . WPINC . '/template-loader.php' );
What is wp()?


wp();
- Parses the URL & runs it through WP_Rewrite
- Sets up query variables for WP_Query
- Runs the query
What is wp()?


wp();
- Parses the URL & runs it through WP_Rewrite
- Sets up query variables for WP_Query
- Runs the query
What is wp()?


wp();
- Parses the URL & runs it through WP_Rewrite
- Sets up query variables for WP_Query
- Runs the query
What is wp()?


wp();
- Parses the URL & runs it through WP_Rewrite
- Sets up query variables for WP_Query
- Runs the query
So, what does this mean?
It means...

Before the theme is even loaded,
WordPress already has your Posts!
Mind == Blown!
In the bootstrap



$wp_the_query = new WP_Query();


$wp_query =& $wp_the_query;
In the bootstrap

// Holds the real main query.
// It should never be modified
$wp_the_query

// A live reference to the main query
$wp_query
In the bootstrap

// Holds the real main query.
// It should never be modified
$wp_the_query

// A live reference to the main query
$wp_query
Back to our queries...
query_posts()
get_posts()
new WP_Query()


All three create new WP_Query objects
query_posts()
goes one step further though
query_posts()

function &query_posts($query) {

    unset($GLOBALS['wp_query']);

    $GLOBALS['wp_query'] = new WP_Query();

    return $GLOBALS['wp_query']->query($query);

}
query_posts()

function &query_posts($query) {
  // Destroys the Global $wp_query variable!
  unset($GLOBALS['wp_query']);

    $GLOBALS['wp_query'] = new WP_Query();

    return $GLOBALS['wp_query']->query($query);

}
query_posts()

function &query_posts($query) {

    unset($GLOBALS['wp_query']);
    // Creates new $wp_query variable
    $GLOBALS['wp_query'] = new WP_Query();

    return $GLOBALS['wp_query']->query($query);

}
I’m sure you’ve all done this...

get_header();
query_posts( 'cat=-1,-2,-3' );
while( have_posts() ) :
  the_post();
endwhile;
wp_reset_query();
get_footer();
That’s running 2* queries!
That’s running 2* queries!
It’s running the query WordPress
thinks you want.
It’s then running your new query
you actually want.
* In actual fact, WP_Query
 doesn’t just run one query.
 It runs four!

 So, that means your template
 is actually running eight queries!
Don’t forget to reset

// Restores the $wp_query reference to $wp_the_query
// Resets the globals
wp_reset_query();

// Resets the globals
wp_reset_postdata();
There’s a better way
Say hello to pre_get_posts

[From the Codex]

The pre_get_posts action gives developers
access to the $query object by reference.
(any changes you make to $query are made
directly to the original object)
Say hello to pre_get_posts

What this means is we can change our
main query before it’s run
pre_get_posts

pre_get_posts fires for every post query:
— get_posts()
— new WP_Query()
— Sidebar widgets
— Admin screen queries
— Everything!
How do we use it?
In functions.php
[example 1]
function my_pre_get_posts( $query ) {
    // Check if the main query and home and not admin
    if ( $query->is_main_query() && is_home() && !is_admin() ) {
     // Display only posts that belong to a certain Category
     $query->set( 'category_name', 'fatuity' );
     // Display only 3 posts per page
     $query->set( 'posts_per_page', '3' );
     return;
     }
}
// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
In functions.php
[example 1]
function my_pre_get_posts( $query ) {
    // Check if the main query and home and not admin
    if ( $query->is_main_query() && is_home() && !is_admin() ) {
     // Display only posts that belong to a certain Category
     $query->set( 'category_name', 'fatuity' );
     // Display only 3 posts per page
     $query->set( 'posts_per_page', '3' );
     return;
     }
}
// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
In functions.php
[example 1]
function my_pre_get_posts( $query ) {
    // Check if the main query and home and not admin
    if ( $query->is_main_query() && is_home() && !is_admin() ) {
      // Display only posts that belong to a certain Category
      $query->set( 'category_name', 'fatuity' );
     // Display only 3 posts per page
     $query->set( 'posts_per_page', '3' );
     return;
     }
}
// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
In functions.php
[example 1]
function my_pre_get_posts( $query ) {
    // Check if the main query and home and not admin
    if ( $query->is_main_query() && is_home() && !is_admin() ) {
     // Display only posts that belong to a certain Category
     $query->set( 'category_name', 'fatuity' );
      // Display only 3 posts per page
      $query->set( 'posts_per_page', '3' );
     return;
     }
}
// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
In functions.php
[example 1]
function my_pre_get_posts( $query ) {
    // Check if the main query and home and not admin
    if ( $query->is_main_query() && is_home() && !is_admin() ) {
     // Display only posts that belong to a certain Category
     $query->set( 'category_name', 'fatuity' );
     // Display only 3 posts per page
     $query->set( 'posts_per_page', '3' );
     return;
     }
}
// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
In functions.php
[example 2]
function my_pre_get_posts( $query ) {
    // Check if the main query and movie CPT archive and not admin
    if($query->is_main_query() && is_post_type_archive('movie') && !is_admin()){

        // Display only posts from a certain taxonomies

        $query->set( 'tax_query', array(
          array( 'taxonomy' => 'genre',
                 'field' => 'slug',
                 'terms' => array ( 'fantasy', 'sci-fi' )
          )
        ) );

        return;
    }

}

// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
In functions.php
[example 2]
function my_pre_get_posts( $query ) {
    // Check if the main query and movie CPT archive and not admin
    if($query->is_main_query() && is_post_type_archive('movie') && !is_admin()){

        // Display only posts from a certain taxonomies

        $query->set( 'tax_query', array(
          array( 'taxonomy' => 'genre',
                 'field' => 'slug',
                 'terms' => array ( 'fantasy', 'sci-fi' )
          )
        ) );

        return;
    }

}

// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
In functions.php
[example 2]
function my_pre_get_posts( $query ) {
    // Check if the main query and movie CPT archive and not admin
    if($query->is_main_query() && is_post_type_archive('movie') && !is_admin()){

        // Display only posts from a certain taxonomies

        $query->set( 'tax_query', array(
          array( 'taxonomy' => 'genre',
                 'field' => 'slug',
                 'terms' => array ( 'fantasy', 'sci-fi' )
          )
        ) );

        return;
    }

}

// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
In functions.php
[example 2]
function my_pre_get_posts( $query ) {
    // Check if the main query and movie CPT archive and not admin
    if($query->is_main_query() && is_post_type_archive('movie') && !is_admin()){

        // Display only posts from a certain taxonomies

        $query->set( 'tax_query', array(
          array( 'taxonomy' => 'genre',
                 'field' => 'slug',
                 'terms' => array ( 'fantasy', 'sci-fi' )
          )
        ) );

        return;
    }

}

// Add our function to the pre_get_posts hook
add_action( 'pre_get_posts', 'my_pre_get_posts' );
Remember...

Do:
— Use pre_get_posts
— Check if it’s the main query by using is_main_query()
— Check it’s not an admin query by using is_admin()
— Check for specific templates using is_home(), etc..
— Set up your query using same parameters as WP_Query()
Don’t:
— Use query_posts()
unless you have a very good reason AND you use wp_reset_query()
( if you really need a secondary query, use new WP_Query() )
References

// You Don’t Know Query - Andrew Nacin
http://wordpress.tv/2012/06/15/andrew-nacin-wp_query
http://www.slideshare.net/andrewnacin/you-dont-know-query-wordcamp-portland-2011

// Make sense of WP Query functions
http://bit.ly/wpsequery

// Querying Posts Without query_posts
http://developer.wordpress.com/2012/05/14/querying-posts-without-query_posts


// pre_get_posts on the WordPress Codex
http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

// Example code on Github
https://github.com/maddisondesigns/wpmelb-nov
That’s all folks!☺

Thanks! Questions?

Mais conteúdo relacionado

Mais procurados

Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentTammy Hart
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Curso Symfony - Clase 2
Curso Symfony - Clase 2Curso Symfony - Clase 2
Curso Symfony - Clase 2Javier Eguiluz
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Kris Wallsmith
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)tompunk
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionNate Abele
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4Javier Eguiluz
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
Api Design
Api DesignApi Design
Api Designsartak
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)andrewnacin
 

Mais procurados (20)

Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Curso Symfony - Clase 2
Curso Symfony - Clase 2Curso Symfony - Clase 2
Curso Symfony - Clase 2
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Symfony 2
Symfony 2Symfony 2
Symfony 2
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
Api Design
Api DesignApi Design
Api Design
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 

Semelhante a WordPress Queries - the right way

You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012l3rady
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryl3rady
 
You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)andrewnacin
 
You Don't Know Query - WordCamp Portland 2011
You Don't Know Query - WordCamp Portland 2011You Don't Know Query - WordCamp Portland 2011
You Don't Know Query - WordCamp Portland 2011andrewnacin
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Yevhen Kotelnytskyi
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Yevhen Kotelnytskyi
 
WP_Query, pre_get_posts, and eliminating query_posts()
WP_Query, pre_get_posts, and eliminating query_posts()WP_Query, pre_get_posts, and eliminating query_posts()
WP_Query, pre_get_posts, and eliminating query_posts()Erick Hitter
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practicesmarkparolisi
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin developmentMostafa Soufi
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking Sebastian Marek
 
Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018
Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018
Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018Damien Carbery
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Michelangelo van Dam
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011Maurizio Pelizzone
 
Apostrophe
ApostropheApostrophe
Apostrophetompunk
 
Custom Post Types and Meta Fields
Custom Post Types and Meta FieldsCustom Post Types and Meta Fields
Custom Post Types and Meta FieldsLiton Arefin
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...WordCamp Sydney
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Working with WP_Query in WordPress
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPresstopher1kenobe
 

Semelhante a WordPress Queries - the right way (20)

You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know query
 
You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)
 
You Don't Know Query - WordCamp Portland 2011
You Don't Know Query - WordCamp Portland 2011You Don't Know Query - WordCamp Portland 2011
You Don't Know Query - WordCamp Portland 2011
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
WP_Query, pre_get_posts, and eliminating query_posts()
WP_Query, pre_get_posts, and eliminating query_posts()WP_Query, pre_get_posts, and eliminating query_posts()
WP_Query, pre_get_posts, and eliminating query_posts()
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practices
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
WP_Query Overview
WP_Query OverviewWP_Query Overview
WP_Query Overview
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
 
Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018
Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018
Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
Apostrophe
ApostropheApostrophe
Apostrophe
 
Custom Post Types and Meta Fields
Custom Post Types and Meta FieldsCustom Post Types and Meta Fields
Custom Post Types and Meta Fields
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Working with WP_Query in WordPress
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPress
 

Mais de Anthony Hortin

Why you should be using WordPress child themes
Why you should be using WordPress child themesWhy you should be using WordPress child themes
Why you should be using WordPress child themesAnthony Hortin
 
Working with WooCommerce Custom Fields
Working with WooCommerce Custom FieldsWorking with WooCommerce Custom Fields
Working with WooCommerce Custom FieldsAnthony Hortin
 
Developing for the WordPress Customizer
Developing for the WordPress CustomizerDeveloping for the WordPress Customizer
Developing for the WordPress CustomizerAnthony Hortin
 
Developing For The WordPress Customizer
Developing For The WordPress CustomizerDeveloping For The WordPress Customizer
Developing For The WordPress CustomizerAnthony Hortin
 
Introduction to Advanced Custom Fields
Introduction to Advanced Custom FieldsIntroduction to Advanced Custom Fields
Introduction to Advanced Custom FieldsAnthony Hortin
 
The Why, When, How of WordPress Child Themes
The Why, When, How of WordPress Child ThemesThe Why, When, How of WordPress Child Themes
The Why, When, How of WordPress Child ThemesAnthony Hortin
 
Essential plugins for your WordPress Website
Essential plugins for your WordPress WebsiteEssential plugins for your WordPress Website
Essential plugins for your WordPress WebsiteAnthony Hortin
 
Building a Membership Site with WooCommerce Memberships
Building a Membership Site with WooCommerce MembershipsBuilding a Membership Site with WooCommerce Memberships
Building a Membership Site with WooCommerce MembershipsAnthony Hortin
 
Building a Membership Site with WooCommerce
Building a Membership Site with WooCommerceBuilding a Membership Site with WooCommerce
Building a Membership Site with WooCommerceAnthony Hortin
 
Getting to Grips with Firebug
Getting to Grips with FirebugGetting to Grips with Firebug
Getting to Grips with FirebugAnthony Hortin
 
Getting to Know WordPress May 2015
Getting to Know WordPress May 2015Getting to Know WordPress May 2015
Getting to Know WordPress May 2015Anthony Hortin
 
25 WordPress Plugins to Complement Your Site
25 WordPress Plugins to Complement Your Site25 WordPress Plugins to Complement Your Site
25 WordPress Plugins to Complement Your SiteAnthony Hortin
 
WordCamp San Francisco & WooCommerce Conference Recap
WordCamp San Francisco & WooCommerce Conference RecapWordCamp San Francisco & WooCommerce Conference Recap
WordCamp San Francisco & WooCommerce Conference RecapAnthony Hortin
 
Creating a multilingual site with WPML
Creating a multilingual site with WPMLCreating a multilingual site with WPML
Creating a multilingual site with WPMLAnthony Hortin
 
WordPress Visual Editor Mastery
WordPress Visual Editor MasteryWordPress Visual Editor Mastery
WordPress Visual Editor MasteryAnthony Hortin
 
Getting to know WordPress
Getting to know WordPressGetting to know WordPress
Getting to know WordPressAnthony Hortin
 
Do's & Don'ts for WordPress Theme Development
Do's & Don'ts for WordPress Theme DevelopmentDo's & Don'ts for WordPress Theme Development
Do's & Don'ts for WordPress Theme DevelopmentAnthony Hortin
 
Getting Started with WooCommerce
Getting Started with WooCommerceGetting Started with WooCommerce
Getting Started with WooCommerceAnthony Hortin
 
Submitting to the WordPress Theme Directory
Submitting to the WordPress Theme DirectorySubmitting to the WordPress Theme Directory
Submitting to the WordPress Theme DirectoryAnthony Hortin
 

Mais de Anthony Hortin (20)

Why you should be using WordPress child themes
Why you should be using WordPress child themesWhy you should be using WordPress child themes
Why you should be using WordPress child themes
 
Working with WooCommerce Custom Fields
Working with WooCommerce Custom FieldsWorking with WooCommerce Custom Fields
Working with WooCommerce Custom Fields
 
WordPress Gutenberg
WordPress GutenbergWordPress Gutenberg
WordPress Gutenberg
 
Developing for the WordPress Customizer
Developing for the WordPress CustomizerDeveloping for the WordPress Customizer
Developing for the WordPress Customizer
 
Developing For The WordPress Customizer
Developing For The WordPress CustomizerDeveloping For The WordPress Customizer
Developing For The WordPress Customizer
 
Introduction to Advanced Custom Fields
Introduction to Advanced Custom FieldsIntroduction to Advanced Custom Fields
Introduction to Advanced Custom Fields
 
The Why, When, How of WordPress Child Themes
The Why, When, How of WordPress Child ThemesThe Why, When, How of WordPress Child Themes
The Why, When, How of WordPress Child Themes
 
Essential plugins for your WordPress Website
Essential plugins for your WordPress WebsiteEssential plugins for your WordPress Website
Essential plugins for your WordPress Website
 
Building a Membership Site with WooCommerce Memberships
Building a Membership Site with WooCommerce MembershipsBuilding a Membership Site with WooCommerce Memberships
Building a Membership Site with WooCommerce Memberships
 
Building a Membership Site with WooCommerce
Building a Membership Site with WooCommerceBuilding a Membership Site with WooCommerce
Building a Membership Site with WooCommerce
 
Getting to Grips with Firebug
Getting to Grips with FirebugGetting to Grips with Firebug
Getting to Grips with Firebug
 
Getting to Know WordPress May 2015
Getting to Know WordPress May 2015Getting to Know WordPress May 2015
Getting to Know WordPress May 2015
 
25 WordPress Plugins to Complement Your Site
25 WordPress Plugins to Complement Your Site25 WordPress Plugins to Complement Your Site
25 WordPress Plugins to Complement Your Site
 
WordCamp San Francisco & WooCommerce Conference Recap
WordCamp San Francisco & WooCommerce Conference RecapWordCamp San Francisco & WooCommerce Conference Recap
WordCamp San Francisco & WooCommerce Conference Recap
 
Creating a multilingual site with WPML
Creating a multilingual site with WPMLCreating a multilingual site with WPML
Creating a multilingual site with WPML
 
WordPress Visual Editor Mastery
WordPress Visual Editor MasteryWordPress Visual Editor Mastery
WordPress Visual Editor Mastery
 
Getting to know WordPress
Getting to know WordPressGetting to know WordPress
Getting to know WordPress
 
Do's & Don'ts for WordPress Theme Development
Do's & Don'ts for WordPress Theme DevelopmentDo's & Don'ts for WordPress Theme Development
Do's & Don'ts for WordPress Theme Development
 
Getting Started with WooCommerce
Getting Started with WooCommerceGetting Started with WooCommerce
Getting Started with WooCommerce
 
Submitting to the WordPress Theme Directory
Submitting to the WordPress Theme DirectorySubmitting to the WordPress Theme Directory
Submitting to the WordPress Theme Directory
 

Último

Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...anilsa9823
 
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
FULL ENJOY - 9953040155 Call Girls in Shahdara | DelhiFULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
FULL ENJOY - 9953040155 Call Girls in Shahdara | DelhiMalviyaNagarCallGirl
 
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad EscortsIslamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escortswdefrd
 
Deira Call Girls # 0522916705 # Call Girls In Deira Dubai || (UAE)
Deira Call Girls # 0522916705 #  Call Girls In Deira Dubai || (UAE)Deira Call Girls # 0522916705 #  Call Girls In Deira Dubai || (UAE)
Deira Call Girls # 0522916705 # Call Girls In Deira Dubai || (UAE)wdefrd
 
FULL ENJOY - 9953040155 Call Girls in Kotla Mubarakpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Kotla Mubarakpur | DelhiFULL ENJOY - 9953040155 Call Girls in Kotla Mubarakpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Kotla Mubarakpur | DelhiMalviyaNagarCallGirl
 
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...gurkirankumar98700
 
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comBridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comthephillipta
 
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...anilsa9823
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...akbard9823
 
Editorial sephora annual report design project
Editorial sephora annual report design projectEditorial sephora annual report design project
Editorial sephora annual report design projecttbatkhuu1
 
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | DelhiFULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | DelhiMalviyaNagarCallGirl
 
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...gurkirankumar98700
 
Jeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson
 
FULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
FULL ENJOY - 9953040155 Call Girls in Wazirabad | DelhiFULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
FULL ENJOY - 9953040155 Call Girls in Wazirabad | DelhiMalviyaNagarCallGirl
 
Alex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson StoryboardAlex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson Storyboardthephillipta
 
exhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxexhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxKurikulumPenilaian
 

Último (20)

Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
 
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
 
FULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
FULL ENJOY - 9953040155 Call Girls in Shahdara | DelhiFULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
FULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
 
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad EscortsIslamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
 
Deira Call Girls # 0522916705 # Call Girls In Deira Dubai || (UAE)
Deira Call Girls # 0522916705 #  Call Girls In Deira Dubai || (UAE)Deira Call Girls # 0522916705 #  Call Girls In Deira Dubai || (UAE)
Deira Call Girls # 0522916705 # Call Girls In Deira Dubai || (UAE)
 
FULL ENJOY - 9953040155 Call Girls in Kotla Mubarakpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Kotla Mubarakpur | DelhiFULL ENJOY - 9953040155 Call Girls in Kotla Mubarakpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Kotla Mubarakpur | Delhi
 
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
 
Indian Deira Call Girls # 0522916705 # Indian Call Girls In Deira Dubai || (UAE)
Indian Deira Call Girls # 0522916705 # Indian Call Girls In Deira Dubai || (UAE)Indian Deira Call Girls # 0522916705 # Indian Call Girls In Deira Dubai || (UAE)
Indian Deira Call Girls # 0522916705 # Indian Call Girls In Deira Dubai || (UAE)
 
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comBridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
 
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
 
Editorial sephora annual report design project
Editorial sephora annual report design projectEditorial sephora annual report design project
Editorial sephora annual report design project
 
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | DelhiFULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
 
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
 
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
 
Jeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around Europe
 
Pakistani Deira Call Girls # 00971589162217 # Pakistani Call Girls In Deira D...
Pakistani Deira Call Girls # 00971589162217 # Pakistani Call Girls In Deira D...Pakistani Deira Call Girls # 00971589162217 # Pakistani Call Girls In Deira D...
Pakistani Deira Call Girls # 00971589162217 # Pakistani Call Girls In Deira D...
 
FULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
FULL ENJOY - 9953040155 Call Girls in Wazirabad | DelhiFULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
FULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
 
Alex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson StoryboardAlex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson Storyboard
 
exhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxexhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptx
 

WordPress Queries - the right way

  • 1. WordPress Queries -the right way Anthony Hortin #wpmelb @maddisondesigns
  • 2. How you’re probably querying query_posts() get_posts() new WP_Query()
  • 4. The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); endwhile; endif;
  • 5. The Loop if ( have_posts() ) // Determines if there’s anything to iterate while ( have_posts() ) : the_post(); endwhile; endif;
  • 6. The Loop if ( have_posts() ) while ( have_posts() ) : // Sets up globals & continues iteration the_post(); endwhile; endif;
  • 7. Anatomy of a WordPress Page The Main Query
  • 8. wp-blog-header.php // Loads the WordPress bootstrap // ie. Sets the ABSPATH constant. // Loads the wp-config.php file etc. require_once( dirname(__FILE__) . '/wp-load.php' ); wp(); // Decide which template files to load // ie. archive.php, index.php etc require_once( ABSPATH . WPINC . '/template-loader.php' );
  • 9. wp-blog-header.php // Loads the WordPress bootstrap // ie. Sets the ABSPATH constant. // Loads the wp-config.php file etc. require_once( dirname(__FILE__) . '/wp-load.php' ); wp(); // Decide which template files to load // ie. archive.php, index.php etc require_once( ABSPATH . WPINC . '/template-loader.php' );
  • 10. wp-blog-header.php // Loads the WordPress bootstrap // ie. Sets the ABSPATH constant. // Loads the wp-config.php file etc. require_once( dirname(__FILE__) . '/wp-load.php' ); wp(); // Decide which template files to load // ie. archive.php, index.php etc require_once( ABSPATH . WPINC . '/template-loader.php' );
  • 11. wp-blog-header.php // Loads the WordPress bootstrap // ie. Sets the ABSPATH constant. // Loads the wp-config.php file etc. require_once( dirname(__FILE__) . '/wp-load.php' ); // Does ALL THE THINGS! wp(); // Decide which template files to load // ie. archive.php, index.php etc require_once( ABSPATH . WPINC . '/template-loader.php' );
  • 12. What is wp()? wp(); - Parses the URL & runs it through WP_Rewrite - Sets up query variables for WP_Query - Runs the query
  • 13. What is wp()? wp(); - Parses the URL & runs it through WP_Rewrite - Sets up query variables for WP_Query - Runs the query
  • 14. What is wp()? wp(); - Parses the URL & runs it through WP_Rewrite - Sets up query variables for WP_Query - Runs the query
  • 15. What is wp()? wp(); - Parses the URL & runs it through WP_Rewrite - Sets up query variables for WP_Query - Runs the query
  • 16. So, what does this mean?
  • 17. It means... Before the theme is even loaded, WordPress already has your Posts!
  • 19. In the bootstrap $wp_the_query = new WP_Query(); $wp_query =& $wp_the_query;
  • 20. In the bootstrap // Holds the real main query. // It should never be modified $wp_the_query // A live reference to the main query $wp_query
  • 21. In the bootstrap // Holds the real main query. // It should never be modified $wp_the_query // A live reference to the main query $wp_query
  • 22. Back to our queries...
  • 24. query_posts() goes one step further though
  • 25. query_posts() function &query_posts($query) { unset($GLOBALS['wp_query']); $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query($query); }
  • 26. query_posts() function &query_posts($query) { // Destroys the Global $wp_query variable! unset($GLOBALS['wp_query']); $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query($query); }
  • 27. query_posts() function &query_posts($query) { unset($GLOBALS['wp_query']); // Creates new $wp_query variable $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query($query); }
  • 28. I’m sure you’ve all done this... get_header(); query_posts( 'cat=-1,-2,-3' ); while( have_posts() ) : the_post(); endwhile; wp_reset_query(); get_footer();
  • 30. That’s running 2* queries! It’s running the query WordPress thinks you want. It’s then running your new query you actually want.
  • 31. * In actual fact, WP_Query doesn’t just run one query. It runs four! So, that means your template is actually running eight queries!
  • 32. Don’t forget to reset // Restores the $wp_query reference to $wp_the_query // Resets the globals wp_reset_query(); // Resets the globals wp_reset_postdata();
  • 34. Say hello to pre_get_posts [From the Codex] The pre_get_posts action gives developers access to the $query object by reference. (any changes you make to $query are made directly to the original object)
  • 35. Say hello to pre_get_posts What this means is we can change our main query before it’s run
  • 36. pre_get_posts pre_get_posts fires for every post query: — get_posts() — new WP_Query() — Sidebar widgets — Admin screen queries — Everything!
  • 37. How do we use it?
  • 38. In functions.php [example 1] function my_pre_get_posts( $query ) { // Check if the main query and home and not admin if ( $query->is_main_query() && is_home() && !is_admin() ) { // Display only posts that belong to a certain Category $query->set( 'category_name', 'fatuity' ); // Display only 3 posts per page $query->set( 'posts_per_page', '3' ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 39. In functions.php [example 1] function my_pre_get_posts( $query ) { // Check if the main query and home and not admin if ( $query->is_main_query() && is_home() && !is_admin() ) { // Display only posts that belong to a certain Category $query->set( 'category_name', 'fatuity' ); // Display only 3 posts per page $query->set( 'posts_per_page', '3' ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 40. In functions.php [example 1] function my_pre_get_posts( $query ) { // Check if the main query and home and not admin if ( $query->is_main_query() && is_home() && !is_admin() ) { // Display only posts that belong to a certain Category $query->set( 'category_name', 'fatuity' ); // Display only 3 posts per page $query->set( 'posts_per_page', '3' ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 41. In functions.php [example 1] function my_pre_get_posts( $query ) { // Check if the main query and home and not admin if ( $query->is_main_query() && is_home() && !is_admin() ) { // Display only posts that belong to a certain Category $query->set( 'category_name', 'fatuity' ); // Display only 3 posts per page $query->set( 'posts_per_page', '3' ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 42. In functions.php [example 1] function my_pre_get_posts( $query ) { // Check if the main query and home and not admin if ( $query->is_main_query() && is_home() && !is_admin() ) { // Display only posts that belong to a certain Category $query->set( 'category_name', 'fatuity' ); // Display only 3 posts per page $query->set( 'posts_per_page', '3' ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 43. In functions.php [example 2] function my_pre_get_posts( $query ) { // Check if the main query and movie CPT archive and not admin if($query->is_main_query() && is_post_type_archive('movie') && !is_admin()){ // Display only posts from a certain taxonomies $query->set( 'tax_query', array( array( 'taxonomy' => 'genre', 'field' => 'slug', 'terms' => array ( 'fantasy', 'sci-fi' ) ) ) ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 44. In functions.php [example 2] function my_pre_get_posts( $query ) { // Check if the main query and movie CPT archive and not admin if($query->is_main_query() && is_post_type_archive('movie') && !is_admin()){ // Display only posts from a certain taxonomies $query->set( 'tax_query', array( array( 'taxonomy' => 'genre', 'field' => 'slug', 'terms' => array ( 'fantasy', 'sci-fi' ) ) ) ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 45. In functions.php [example 2] function my_pre_get_posts( $query ) { // Check if the main query and movie CPT archive and not admin if($query->is_main_query() && is_post_type_archive('movie') && !is_admin()){ // Display only posts from a certain taxonomies $query->set( 'tax_query', array( array( 'taxonomy' => 'genre', 'field' => 'slug', 'terms' => array ( 'fantasy', 'sci-fi' ) ) ) ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 46. In functions.php [example 2] function my_pre_get_posts( $query ) { // Check if the main query and movie CPT archive and not admin if($query->is_main_query() && is_post_type_archive('movie') && !is_admin()){ // Display only posts from a certain taxonomies $query->set( 'tax_query', array( array( 'taxonomy' => 'genre', 'field' => 'slug', 'terms' => array ( 'fantasy', 'sci-fi' ) ) ) ); return; } } // Add our function to the pre_get_posts hook add_action( 'pre_get_posts', 'my_pre_get_posts' );
  • 47. Remember... Do: — Use pre_get_posts — Check if it’s the main query by using is_main_query() — Check it’s not an admin query by using is_admin() — Check for specific templates using is_home(), etc.. — Set up your query using same parameters as WP_Query() Don’t: — Use query_posts() unless you have a very good reason AND you use wp_reset_query() ( if you really need a secondary query, use new WP_Query() )
  • 48. References // You Don’t Know Query - Andrew Nacin http://wordpress.tv/2012/06/15/andrew-nacin-wp_query http://www.slideshare.net/andrewnacin/you-dont-know-query-wordcamp-portland-2011 // Make sense of WP Query functions http://bit.ly/wpsequery // Querying Posts Without query_posts http://developer.wordpress.com/2012/05/14/querying-posts-without-query_posts // pre_get_posts on the WordPress Codex http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts // Example code on Github https://github.com/maddisondesigns/wpmelb-nov

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. wp-blog-header() -> wp-load.php -> wp-config.php -> wp-settings.php\n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n