SlideShare ist ein Scribd-Unternehmen logo
1 von 49
Downloaden Sie, um offline zu lesen
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?

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Escort Service in Al Barsha +971509530047 UAE
Escort Service in Al Barsha +971509530047 UAEEscort Service in Al Barsha +971509530047 UAE
Escort Service in Al Barsha +971509530047 UAEvecevep119
 
Bai tap thuc hanh Anh 6 Mai Lan Huong.docx
Bai tap thuc hanh Anh 6 Mai Lan Huong.docxBai tap thuc hanh Anh 6 Mai Lan Huong.docx
Bai tap thuc hanh Anh 6 Mai Lan Huong.docxbichthuyt81
 
Kristy Soto's Industrial design Portfolio
Kristy Soto's Industrial design PortfolioKristy Soto's Industrial design Portfolio
Kristy Soto's Industrial design PortfolioKristySoto
 
The Masque of the Red Death Storyboard 2023
The Masque of the Red Death Storyboard 2023The Masque of the Red Death Storyboard 2023
The Masque of the Red Death Storyboard 2023magalybtapia
 
San Jon Motel, Motel/Residence, San Jon, NM
San Jon Motel, Motel/Residence, San Jon, NMSan Jon Motel, Motel/Residence, San Jon, NM
San Jon Motel, Motel/Residence, San Jon, NMroute66connected
 
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call GirlJvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girllijeho2176
 
My Morning Routine - Storyboard Sequence
My Morning Routine - Storyboard SequenceMy Morning Routine - Storyboard Sequence
My Morning Routine - Storyboard Sequenceartbysarahrodriguezg
 
Roadrunner Motel, Motel/Residence. Tucumcari, NM
Roadrunner Motel, Motel/Residence. Tucumcari, NMRoadrunner Motel, Motel/Residence. Tucumcari, NM
Roadrunner Motel, Motel/Residence. Tucumcari, NMroute66connected
 
Americana Motel, Motel/Residence, Tucumcari, NM
Americana Motel, Motel/Residence, Tucumcari, NMAmericana Motel, Motel/Residence, Tucumcari, NM
Americana Motel, Motel/Residence, Tucumcari, NMroute66connected
 
Escort Service in Abu Dhabi +971509530047 UAE
Escort Service in Abu Dhabi +971509530047 UAEEscort Service in Abu Dhabi +971509530047 UAE
Escort Service in Abu Dhabi +971509530047 UAEvecevep119
 
SLIDESHARE. ART OF THE ROMANTIC PERIOD/ROMANTICISM Art
SLIDESHARE. ART OF THE ROMANTIC PERIOD/ROMANTICISM ArtSLIDESHARE. ART OF THE ROMANTIC PERIOD/ROMANTICISM Art
SLIDESHARE. ART OF THE ROMANTIC PERIOD/ROMANTICISM ArtChum26
 
Element of art, Transcreation and usions and overlapping and interrelated ele...
Element of art, Transcreation and usions and overlapping and interrelated ele...Element of art, Transcreation and usions and overlapping and interrelated ele...
Element of art, Transcreation and usions and overlapping and interrelated ele...jheramypagoyoiman801
 
Rückenfigur ... back figure in paintings.ppsx
Rückenfigur ... back figure in paintings.ppsxRückenfigur ... back figure in paintings.ppsx
Rückenfigur ... back figure in paintings.ppsxguimera
 
Olympia Cafe, Restaurants-cafes, Albuquerque, NM
Olympia Cafe, Restaurants-cafes, Albuquerque, NMOlympia Cafe, Restaurants-cafes, Albuquerque, NM
Olympia Cafe, Restaurants-cafes, Albuquerque, NMroute66connected
 
Abu Dhabi Housewife Call Girls +971509530047 Abu Dhabi Call Girls
Abu Dhabi Housewife Call Girls +971509530047 Abu Dhabi Call GirlsAbu Dhabi Housewife Call Girls +971509530047 Abu Dhabi Call Girls
Abu Dhabi Housewife Call Girls +971509530047 Abu Dhabi Call Girlshayawit234
 
Hiway Motel, Motel/Residence, Albuquerque NM
Hiway Motel, Motel/Residence, Albuquerque NMHiway Motel, Motel/Residence, Albuquerque NM
Hiway Motel, Motel/Residence, Albuquerque NMroute66connected
 
ReverseEngineerBoards_StarWarsEpisodeIII
ReverseEngineerBoards_StarWarsEpisodeIIIReverseEngineerBoards_StarWarsEpisodeIII
ReverseEngineerBoards_StarWarsEpisodeIIIartbysarahrodriguezg
 
Al Barsha Housewife Call Girls +971509530047 Al Barsha Call Girls
Al Barsha Housewife Call Girls +971509530047 Al Barsha Call GirlsAl Barsha Housewife Call Girls +971509530047 Al Barsha Call Girls
Al Barsha Housewife Call Girls +971509530047 Al Barsha Call Girlshayawit234
 
Olivia Cox HITCS final lyric booklet.pdf
Olivia Cox HITCS final lyric booklet.pdfOlivia Cox HITCS final lyric booklet.pdf
Olivia Cox HITCS final lyric booklet.pdfLauraFagan6
 
FORTH QUARTER MAPEH7-PHILIPPINE FESTIVALS.pptx
FORTH QUARTER MAPEH7-PHILIPPINE FESTIVALS.pptxFORTH QUARTER MAPEH7-PHILIPPINE FESTIVALS.pptx
FORTH QUARTER MAPEH7-PHILIPPINE FESTIVALS.pptxJadeTamme
 

Kürzlich hochgeladen (20)

Escort Service in Al Barsha +971509530047 UAE
Escort Service in Al Barsha +971509530047 UAEEscort Service in Al Barsha +971509530047 UAE
Escort Service in Al Barsha +971509530047 UAE
 
Bai tap thuc hanh Anh 6 Mai Lan Huong.docx
Bai tap thuc hanh Anh 6 Mai Lan Huong.docxBai tap thuc hanh Anh 6 Mai Lan Huong.docx
Bai tap thuc hanh Anh 6 Mai Lan Huong.docx
 
Kristy Soto's Industrial design Portfolio
Kristy Soto's Industrial design PortfolioKristy Soto's Industrial design Portfolio
Kristy Soto's Industrial design Portfolio
 
The Masque of the Red Death Storyboard 2023
The Masque of the Red Death Storyboard 2023The Masque of the Red Death Storyboard 2023
The Masque of the Red Death Storyboard 2023
 
San Jon Motel, Motel/Residence, San Jon, NM
San Jon Motel, Motel/Residence, San Jon, NMSan Jon Motel, Motel/Residence, San Jon, NM
San Jon Motel, Motel/Residence, San Jon, NM
 
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call GirlJvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
 
My Morning Routine - Storyboard Sequence
My Morning Routine - Storyboard SequenceMy Morning Routine - Storyboard Sequence
My Morning Routine - Storyboard Sequence
 
Roadrunner Motel, Motel/Residence. Tucumcari, NM
Roadrunner Motel, Motel/Residence. Tucumcari, NMRoadrunner Motel, Motel/Residence. Tucumcari, NM
Roadrunner Motel, Motel/Residence. Tucumcari, NM
 
Americana Motel, Motel/Residence, Tucumcari, NM
Americana Motel, Motel/Residence, Tucumcari, NMAmericana Motel, Motel/Residence, Tucumcari, NM
Americana Motel, Motel/Residence, Tucumcari, NM
 
Escort Service in Abu Dhabi +971509530047 UAE
Escort Service in Abu Dhabi +971509530047 UAEEscort Service in Abu Dhabi +971509530047 UAE
Escort Service in Abu Dhabi +971509530047 UAE
 
SLIDESHARE. ART OF THE ROMANTIC PERIOD/ROMANTICISM Art
SLIDESHARE. ART OF THE ROMANTIC PERIOD/ROMANTICISM ArtSLIDESHARE. ART OF THE ROMANTIC PERIOD/ROMANTICISM Art
SLIDESHARE. ART OF THE ROMANTIC PERIOD/ROMANTICISM Art
 
Element of art, Transcreation and usions and overlapping and interrelated ele...
Element of art, Transcreation and usions and overlapping and interrelated ele...Element of art, Transcreation and usions and overlapping and interrelated ele...
Element of art, Transcreation and usions and overlapping and interrelated ele...
 
Rückenfigur ... back figure in paintings.ppsx
Rückenfigur ... back figure in paintings.ppsxRückenfigur ... back figure in paintings.ppsx
Rückenfigur ... back figure in paintings.ppsx
 
Olympia Cafe, Restaurants-cafes, Albuquerque, NM
Olympia Cafe, Restaurants-cafes, Albuquerque, NMOlympia Cafe, Restaurants-cafes, Albuquerque, NM
Olympia Cafe, Restaurants-cafes, Albuquerque, NM
 
Abu Dhabi Housewife Call Girls +971509530047 Abu Dhabi Call Girls
Abu Dhabi Housewife Call Girls +971509530047 Abu Dhabi Call GirlsAbu Dhabi Housewife Call Girls +971509530047 Abu Dhabi Call Girls
Abu Dhabi Housewife Call Girls +971509530047 Abu Dhabi Call Girls
 
Hiway Motel, Motel/Residence, Albuquerque NM
Hiway Motel, Motel/Residence, Albuquerque NMHiway Motel, Motel/Residence, Albuquerque NM
Hiway Motel, Motel/Residence, Albuquerque NM
 
ReverseEngineerBoards_StarWarsEpisodeIII
ReverseEngineerBoards_StarWarsEpisodeIIIReverseEngineerBoards_StarWarsEpisodeIII
ReverseEngineerBoards_StarWarsEpisodeIII
 
Al Barsha Housewife Call Girls +971509530047 Al Barsha Call Girls
Al Barsha Housewife Call Girls +971509530047 Al Barsha Call GirlsAl Barsha Housewife Call Girls +971509530047 Al Barsha Call Girls
Al Barsha Housewife Call Girls +971509530047 Al Barsha Call Girls
 
Olivia Cox HITCS final lyric booklet.pdf
Olivia Cox HITCS final lyric booklet.pdfOlivia Cox HITCS final lyric booklet.pdf
Olivia Cox HITCS final lyric booklet.pdf
 
FORTH QUARTER MAPEH7-PHILIPPINE FESTIVALS.pptx
FORTH QUARTER MAPEH7-PHILIPPINE FESTIVALS.pptxFORTH QUARTER MAPEH7-PHILIPPINE FESTIVALS.pptx
FORTH QUARTER MAPEH7-PHILIPPINE FESTIVALS.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

Hinweis der Redaktion

  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