SlideShare una empresa de Scribd logo
1 de 53
You Don’t Know Query

 WordCamp Edinburgh UK
     14-15 July 2012
Scott Cariss aka Brady
• Lead developer at Philosophy Design.

• Moderator at WordPress Answers
  (http://wordpress.stackexchange.com)

• WordPress plugin developer and enthusiast

scott@philosophydesign.com
@l3rady on Twitter
You Don’t Know Query
What do you know?
Conditional Tags
is_author(), is_home(), etc.
Who has ever heard of query_posts()?
Ways to query
query_posts()
new WP_Query()
get_posts()
The loop
if( have_posts() )
   while( have_posts() ):
     the_post();

  endwhile();
What don’t you know?
Every query object has its own
               methods
is_author() is the same as calling
$wp_query->is_author()
function is_author()
{
  global $wp_query;

    return $wp_query->is_author();
}
If you do:
$my_query = new WP_Query( $query );

You can do:
while ( $my_query->have_posts( ) ) :
  $my_query->the_post( ); endwhile;
wp_reset_postdata( );
But why do we call things like
wp_reset_postdata( ) and
wp_reset_query( )?

What about using query_posts( )?

How can you alter a query? What about
the main query?
What is the main query, and why
         should I care?




     Let's dig in
wp-blog-header.php
// Load the WordPress bootstrap require
dirname( __FILE__ ) . '/wp-load.php';




// Decide which template files to load
ABSPATH . WPINC . '/template-loader.php';
Let’s look in the bootstrap:
$wp_the_query = new WP_Query();
$wp_query =& $wp_the_query;
Quick lesson on PHP references
$a = 4;
$b =& $a;

$b = 2;
var_dump( $a ); // int(2)

$a = 6;
var_dump( $b ); // int(6)
So:
The real main query is in
$wp_the_query.

And a live copy of it is stored in
$wp_query
wp-blog-header.php
// Load the WordPress bootstrap require
dirname( __FILE__ ) . '/wp-load.php';

// Do magic
wp();

// Decide which template files to load
ABSPATH . WPINC . '/template-loader.php';
What is that wp() call?
function wp( $query_vars = '' )
{
  global $wp;

    $wp->main( $query_vars );
}
Holy $!@?, what just happened?
In the bootstrap:
$wp = new WP()

So there’s a wp() function, and a WP class.
class WP
{
  ...
  function main( )
  {
      $this->init( );
      $this->parse_request( );
      $this->send_headers( );
      $this->query_posts( );
      $this->handle_404( );
      $this->register_globals( );
  }
  ...
}
class WP
{
  ...
  function main( )
  {
      $this->init( );
      $this->parse_request( );
      $this->send_headers( );
      $this->query_posts( );
      $this->handle_404( );
      $this->register_globals( );
  }
  ...
}
WP::parse_request( )
Parses the URL using WP_Rewrite
Sets up query variables for WP_Query

WP::query_posts( )
{
  global $wp_the_query;
  $wp_the_query->query( $this->query_vars );
}
What do we get?
SELECT SQL_CALC_FOUND_ROWS
  wp_posts.* FROM
wp_posts WHERE 1=1
  AND wp_posts.post_type = 'post‘
  AND wp_posts.post_status = 'publish' ORDER
BY wp_posts.post_date DESC LIMIT 0, 10
wp-blog-header.php
// Load WordPress
dirname( __FILE__ ) . '/wp-load.php';

// Parse what to query, and query it.
wp();

// Load the theme.
ABSPATH . WPINC . '/template-loader.php';
Before we get to the theme, we have
             your posts.
Are we clear so far?
Then why do we do this?
query_posts( 'author=5' );
get_header( );

while( have_posts( ) ) :
  the_post( );
endwhile;

get_footer( );
That’s running 2* queries!
One, the query WordPress
thought we wanted.

Two, this new one you’re
actually going to use.
* Actually, WP_Query doesn't run just one
query. It usually runs four.
1. Get me my posts: SELECT
     SQL_CALC_FOUND_ROWS …
     FROM wp_posts LIMIT 0, 10
2. How many posts exist?
     SELECT FOUND_ROWS()
3. Pull down all metadata for these posts.
4. Pull down all terms for these posts.
Instead of query_posts()?
We can use this:

// In WP::parse_request()

$this->query_vars = apply_filters(
  'request', $this->query_vars );
We can modify query variables in mid
               air:
function brady_filter_out_author( $qvs )
{
  if( ! Isset( $qvs*‘author’+ ) )
     $qvs*‘author’+ = ‘-5’;

  return $qvs;
}
add_filter( “request”, “brady_filter_out_author”);
Powerful, but lacks context.
Problems:

1. Conditional tags don’t work yet.

2. Only works on the main query.

3. WP_Query is way cooler.
Introducing pre_get_posts
class WP_Query
{
   ...
   function &get_posts()
   {
     $this->parse_query();
     // OMG! Conditional tags are available!!
     do_action_ref_array( 'pre_get_posts', array( &$this ) );
   }
   ...
}
Lets kill off query_posts()!
function brady_alter_home( $query )
{
  if ( $query->is_home( ) )
     $query->set( 'author', '-5' );
}
add_action(
  'pre_get_posts', ‘brady_alter_home' );
Still with us?
Good ‘cause here’s where things get hairy.
‘request’ fires for the main query only.

‘pre_get_posts’ fires for every post query:

•   get_posts()
•   new WP_Query()
•   That random recent posts widget.
•   Everything.
What if I just want it on the
       main query?
$wp_the_query makes a
  triumphant return.
Main query only!
function brady_alter_home( $query )
{
  if ( $query->is_home( ) &&
        $wp_the_query === $query )
     $query->set( 'author', '-5' );
}
add_action(
  'pre_get_posts', ‘brady_alter_home' );
Hmm. How does this work?
$wp_the_query should never be modified. It
 holds the main query, forever.

$wp_query keeps a live reference to
 $wp_the_query, unless you use query_posts().
query_posts( 'author=-5' );
while ( have_posts( ) ) :
  the_post( );
endwhile;
wp_reset_query( );
class WP_Query
{
   ...
   function &query_posts( $query )
   {
       // Break the reference to $wp_the_query
       unset( $wp_query );
       $wp_query =& new WP_Query( $query );
       ...
   }
   ...
}
query_posts( 'author=-5' );
while ( have_posts( ) ) :
  the_post( );
endwhile;
wp_reset_query( );
class WP_Query
{
  ...
  function wp_reset_query( )
  {
      // Restore the reference to $wp_the_query
      unset( $wp_query );
      $wp_query =& $wp_the_query;
      // Reset the globals, too.
      wp_reset_postdata( );
      ...
  }
  ....
}
Calling the_post( )? wp_reset_query( ) will reset
  $wp_query and and the globals.

Calling $my_query->the_post( )?
  wp_reset_postdata( ) will reset the globals.
Since WordPress 3.3!
Rather than:
$wp_the_query === $other_query_object

You‘re able to call:
$other_query_object->is_main_query( )
Some Lessons
Every WP_Query object has methods that mimic
  the global conditional tags.

The global conditional tags apply to
  $wp_query, the main or current query.

$wp_query is always the main query, unless you
 use query_posts( ). Restore it with
 wp_reset_query( ).
And finally
request is a nice hook. pre_get_posts is more
  powerful and flexible. Just use it properly.

Always check if you're modifying the main query
  using $query->is_main_query( )

$query === $wp_the_query before 3.3
Demo
Thank you! Any questions?

Más contenido relacionado

La actualidad más candente

Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
jQuery Plugin Creation
jQuery Plugin CreationjQuery Plugin Creation
jQuery Plugin Creation
benalman
 

La actualidad más candente (20)

Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, Again
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Hooks WCSD12
Hooks WCSD12Hooks WCSD12
Hooks WCSD12
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
WCLV13 JavaScript
WCLV13 JavaScriptWCLV13 JavaScript
WCLV13 JavaScript
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment Caching
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
 
jQuery Plugin Creation
jQuery Plugin CreationjQuery Plugin Creation
jQuery Plugin Creation
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
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()
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019
 

Similar a You don’t know query - WordCamp UK Edinburgh 2012

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
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
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
Tammy Hart
 

Similar a You don’t know query - WordCamp UK Edinburgh 2012 (20)

Working with WP_Query in WordPress
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPress
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
 
Can WordPress really do that? A case study of vierderduer.no
Can WordPress really do that? A case study of vierderduer.noCan WordPress really do that? A case study of vierderduer.no
Can WordPress really do that? A case study of vierderduer.no
 
Custom Database Queries in WordPress
Custom Database Queries in WordPressCustom Database Queries in WordPress
Custom Database Queries in WordPress
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 
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)
 
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
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
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
Apostrophe
ApostropheApostrophe
Apostrophe
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

You don’t know query - WordCamp UK Edinburgh 2012

  • 1. You Don’t Know Query WordCamp Edinburgh UK 14-15 July 2012
  • 2. Scott Cariss aka Brady • Lead developer at Philosophy Design. • Moderator at WordPress Answers (http://wordpress.stackexchange.com) • WordPress plugin developer and enthusiast scott@philosophydesign.com @l3rady on Twitter
  • 4. What do you know?
  • 6. Who has ever heard of query_posts()?
  • 7. Ways to query query_posts() new WP_Query() get_posts()
  • 8. The loop if( have_posts() ) while( have_posts() ): the_post(); endwhile();
  • 10. Every query object has its own methods is_author() is the same as calling $wp_query->is_author()
  • 11. function is_author() { global $wp_query; return $wp_query->is_author(); }
  • 12. If you do: $my_query = new WP_Query( $query ); You can do: while ( $my_query->have_posts( ) ) : $my_query->the_post( ); endwhile; wp_reset_postdata( );
  • 13. But why do we call things like wp_reset_postdata( ) and wp_reset_query( )? What about using query_posts( )? How can you alter a query? What about the main query?
  • 14. What is the main query, and why should I care? Let's dig in
  • 15. wp-blog-header.php // Load the WordPress bootstrap require dirname( __FILE__ ) . '/wp-load.php'; // Decide which template files to load ABSPATH . WPINC . '/template-loader.php';
  • 16. Let’s look in the bootstrap: $wp_the_query = new WP_Query(); $wp_query =& $wp_the_query;
  • 17. Quick lesson on PHP references $a = 4; $b =& $a; $b = 2; var_dump( $a ); // int(2) $a = 6; var_dump( $b ); // int(6)
  • 18. So: The real main query is in $wp_the_query. And a live copy of it is stored in $wp_query
  • 19. wp-blog-header.php // Load the WordPress bootstrap require dirname( __FILE__ ) . '/wp-load.php'; // Do magic wp(); // Decide which template files to load ABSPATH . WPINC . '/template-loader.php';
  • 20. What is that wp() call? function wp( $query_vars = '' ) { global $wp; $wp->main( $query_vars ); }
  • 21. Holy $!@?, what just happened?
  • 22. In the bootstrap: $wp = new WP() So there’s a wp() function, and a WP class.
  • 23. class WP { ... function main( ) { $this->init( ); $this->parse_request( ); $this->send_headers( ); $this->query_posts( ); $this->handle_404( ); $this->register_globals( ); } ... }
  • 24. class WP { ... function main( ) { $this->init( ); $this->parse_request( ); $this->send_headers( ); $this->query_posts( ); $this->handle_404( ); $this->register_globals( ); } ... }
  • 25. WP::parse_request( ) Parses the URL using WP_Rewrite Sets up query variables for WP_Query WP::query_posts( ) { global $wp_the_query; $wp_the_query->query( $this->query_vars ); }
  • 26. What do we get? SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post‘ AND wp_posts.post_status = 'publish' ORDER BY wp_posts.post_date DESC LIMIT 0, 10
  • 27. wp-blog-header.php // Load WordPress dirname( __FILE__ ) . '/wp-load.php'; // Parse what to query, and query it. wp(); // Load the theme. ABSPATH . WPINC . '/template-loader.php';
  • 28. Before we get to the theme, we have your posts. Are we clear so far?
  • 29. Then why do we do this? query_posts( 'author=5' ); get_header( ); while( have_posts( ) ) : the_post( ); endwhile; get_footer( );
  • 30. That’s running 2* queries! One, the query WordPress thought we wanted. Two, this new one you’re actually going to use.
  • 31. * Actually, WP_Query doesn't run just one query. It usually runs four.
  • 32. 1. Get me my posts: SELECT SQL_CALC_FOUND_ROWS … FROM wp_posts LIMIT 0, 10 2. How many posts exist? SELECT FOUND_ROWS() 3. Pull down all metadata for these posts. 4. Pull down all terms for these posts.
  • 33. Instead of query_posts()? We can use this: // In WP::parse_request() $this->query_vars = apply_filters( 'request', $this->query_vars );
  • 34. We can modify query variables in mid air: function brady_filter_out_author( $qvs ) { if( ! Isset( $qvs*‘author’+ ) ) $qvs*‘author’+ = ‘-5’; return $qvs; } add_filter( “request”, “brady_filter_out_author”);
  • 35. Powerful, but lacks context. Problems: 1. Conditional tags don’t work yet. 2. Only works on the main query. 3. WP_Query is way cooler.
  • 36. Introducing pre_get_posts class WP_Query { ... function &get_posts() { $this->parse_query(); // OMG! Conditional tags are available!! do_action_ref_array( 'pre_get_posts', array( &$this ) ); } ... }
  • 37. Lets kill off query_posts()! function brady_alter_home( $query ) { if ( $query->is_home( ) ) $query->set( 'author', '-5' ); } add_action( 'pre_get_posts', ‘brady_alter_home' );
  • 38. Still with us? Good ‘cause here’s where things get hairy.
  • 39. ‘request’ fires for the main query only. ‘pre_get_posts’ fires for every post query: • get_posts() • new WP_Query() • That random recent posts widget. • Everything.
  • 40. What if I just want it on the main query?
  • 41. $wp_the_query makes a triumphant return.
  • 42. Main query only! function brady_alter_home( $query ) { if ( $query->is_home( ) && $wp_the_query === $query ) $query->set( 'author', '-5' ); } add_action( 'pre_get_posts', ‘brady_alter_home' );
  • 43. Hmm. How does this work? $wp_the_query should never be modified. It holds the main query, forever. $wp_query keeps a live reference to $wp_the_query, unless you use query_posts().
  • 44. query_posts( 'author=-5' ); while ( have_posts( ) ) : the_post( ); endwhile; wp_reset_query( );
  • 45. class WP_Query { ... function &query_posts( $query ) { // Break the reference to $wp_the_query unset( $wp_query ); $wp_query =& new WP_Query( $query ); ... } ... }
  • 46. query_posts( 'author=-5' ); while ( have_posts( ) ) : the_post( ); endwhile; wp_reset_query( );
  • 47. class WP_Query { ... function wp_reset_query( ) { // Restore the reference to $wp_the_query unset( $wp_query ); $wp_query =& $wp_the_query; // Reset the globals, too. wp_reset_postdata( ); ... } .... }
  • 48. Calling the_post( )? wp_reset_query( ) will reset $wp_query and and the globals. Calling $my_query->the_post( )? wp_reset_postdata( ) will reset the globals.
  • 49. Since WordPress 3.3! Rather than: $wp_the_query === $other_query_object You‘re able to call: $other_query_object->is_main_query( )
  • 50. Some Lessons Every WP_Query object has methods that mimic the global conditional tags. The global conditional tags apply to $wp_query, the main or current query. $wp_query is always the main query, unless you use query_posts( ). Restore it with wp_reset_query( ).
  • 51. And finally request is a nice hook. pre_get_posts is more powerful and flexible. Just use it properly. Always check if you're modifying the main query using $query->is_main_query( ) $query === $wp_the_query before 3.3
  • 52. Demo
  • 53. Thank you! Any questions?