SlideShare a Scribd company logo
1 of 33
WordCamp Pune 2013
Savita Soni, co-founder AmiWorks & chief-poet for WPoets
Twitter @savitas
Power of WP_Query
Ways to fetch posts & related data

•   query_posts()
•   new WP_Query()
•   get_posts()
•   $wpdb global db object
query_posts()
How query_posts() looks

query_posts( $args );
while ( have_posts() ) :
        the_post();
        //the_title(), the_ID(), the_permalink() etc..
endwhile;

// Reset Query
wp_reset_query();
new WP_Query()
How WP_Query() looks
// The Query
$the_query = new WP_Query( $args );

// The Loop
while ( $the_query->have_posts() ) :
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
endwhile;
wp_reset_postdata();
get_posts()
How get_posts() looks

<?php
global $post;
$args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
        foreach( $myposts as $post ) :
                setup_postdata($post); ?>
                <li><a href="<?php the_permalink(); ?>">
                <?php the_title(); ?></a></li>
        <?php endforeach;
?>
This all we already know?
So lets see something which we may not know...
Conditional tags

is_author()
is_home()
is_archive()


we know this as well and use them frequently…
But have you seen this?

$wp_query = new WP_Query( $args );
$wp_query->is_author()
$wp_query->is_home()
$wp_query->is_archive()


Yes every query object has its own methods
so we can do this as well

$my_query = new WP_Query( $args );
while( $my_query->have_posts() ):
      $my_query->the_post();
      if( $my_query->is_author()){
            // do something for author
     }
endwhile;
wp_reset_postdata();
why we always needs to call

wp_reset_query()
wp_reset_postdata();


with query_posts() or WP_Query()
because when we do this

query_posts( 'cat=5');
while ( have_posts() ) :
       the_post();
       //the_title(), the_ID(), the_permalink() etc..
endwhile;


We have altered the main query...
How?
global $wp_query; //this is the main query object
Do anyone know this?
$wp_the_query

So the real main query object $wp_the_query
and $wp_query is the live copy of $wp_the_query
it is something like


$wp_the_query = new WP_Query();
$wp_query = &$wp_the_query;
when we call query_posts(), it works like this



function query_posts($query) {
      $GLOBALS['wp_query'] = new WP_Query();
      return $GLOBALS['wp_query']->query($query);
}
and when we call wp_reset_query()



function wp_reset_query() {
       $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
       wp_reset_postdata();
}
how many query(s) get called when we call
WP_Query()?




Is it running only one query with your passed
arguments????
it is running 4 queries

1. Select SQL_CALC_FOUND_ROWS....FROM wp_posts
limit 0,10

2. Select FOUND_ROWS();

3. Get all metadata attached to these posts.

4. Get all terms for these posts.
off some arguments selectively

new WP_Query(
     array(
            'no_found_rows' => false,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false
     )
)
what if I need to modify the main query only?




Use pre_get_posts hook
function exclude_category( $query ) {
       $query->set( 'cat', '-1,-1347' );
}
add_action( 'pre_get_posts', 'exclude_category' );
Now problem with this...

it gets called for every post query
get_posts()
WP_Query()
query_posts()
what if I just need it for home page query?

now $wp_the_query object will help

function exclude_category( $query ) {
      global $wp_the_query;
      if( $wp_the_query == $query
             and $query->home()){
             $query->set( 'cat', '-1,-1347' );
      }
}
add_action( 'pre_get_posts', 'exclude_category' );
After WordPress 3.3 we have an awesome function

is_main_query()
So rather than writing

function exclude_category( $query ) {
      global $wp_the_query;
      //if( $wp_the_query == $query and $query->home())
      if( $query->is_main_query() and $query->home()) {
              $query->set( 'cat', '-1,-1347' );
}
Conclusion

 Try to avoid using query_posts()
 If query_posts() is used then reset it with
  wp_reset_query()
 Use pre_get_posts hook to alter main query &
  use it with is_main_query() condition tag
Thanks



Email: savita@amiworks.com
      Twitter: @savitas

More Related Content

What's hot

Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
 
Database performance 101
Database performance 101Database performance 101
Database performance 101Leon Fayer
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainDrewAPicture
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowKacper Gunia
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteLeonardo Proietti
 

What's hot (20)

Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
Database performance 101
Database performance 101Database performance 101
Database performance 101
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
Hooks WCSD12
Hooks WCSD12Hooks WCSD12
Hooks WCSD12
 
WCLV13 JavaScript
WCLV13 JavaScriptWCLV13 JavaScript
WCLV13 JavaScript
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, Again
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 

Similar to Wp query

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
 
The Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the QueryThe Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the QueryChris Olbekson
 
WordPress Queries - the right way
WordPress Queries - the right wayWordPress Queries - the right way
WordPress Queries - the right wayAnthony Hortin
 
Getting Creative with WordPress Queries
Getting Creative with WordPress QueriesGetting Creative with WordPress Queries
Getting Creative with WordPress QueriesDrewAPicture
 
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 2014Cliff Seal
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingChris Reynolds
 
[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 2018Adam Tomat
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Yevhen Kotelnytskyi
 
Working with WP_Query in WordPress
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPresstopher1kenobe
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Cliff Seal
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
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? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Yevhen Kotelnytskyi
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Getting to The Loop - London Wordpress Meetup July 28th
Getting to The Loop - London Wordpress Meetup  July 28thGetting to The Loop - London Wordpress Meetup  July 28th
Getting to The Loop - London Wordpress Meetup July 28thChris Adams
 

Similar to Wp query (20)

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
 
The Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the QueryThe Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the Query
 
WordPress Queries - the right way
WordPress Queries - the right wayWordPress Queries - the right way
WordPress Queries - the right way
 
Getting Creative with WordPress Queries
Getting Creative with WordPress QueriesGetting Creative with WordPress Queries
Getting Creative with WordPress Queries
 
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
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
 
[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?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
 
Working with WP_Query in WordPress
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPress
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Oops in php
Oops in phpOops in php
Oops in php
 
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? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Getting to The Loop - London Wordpress Meetup July 28th
Getting to The Loop - London Wordpress Meetup  July 28thGetting to The Loop - London Wordpress Meetup  July 28th
Getting to The Loop - London Wordpress Meetup July 28th
 

Wp query

  • 2. Savita Soni, co-founder AmiWorks & chief-poet for WPoets Twitter @savitas
  • 4. Ways to fetch posts & related data • query_posts() • new WP_Query() • get_posts() • $wpdb global db object
  • 6. How query_posts() looks query_posts( $args ); while ( have_posts() ) : the_post(); //the_title(), the_ID(), the_permalink() etc.. endwhile; // Reset Query wp_reset_query();
  • 8. How WP_Query() looks // The Query $the_query = new WP_Query( $args ); // The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; endwhile; wp_reset_postdata();
  • 10. How get_posts() looks <?php global $post; $args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a></li> <?php endforeach; ?>
  • 11. This all we already know?
  • 12. So lets see something which we may not know...
  • 13. Conditional tags is_author() is_home() is_archive() we know this as well and use them frequently…
  • 14. But have you seen this? $wp_query = new WP_Query( $args ); $wp_query->is_author() $wp_query->is_home() $wp_query->is_archive() Yes every query object has its own methods
  • 15. so we can do this as well $my_query = new WP_Query( $args ); while( $my_query->have_posts() ): $my_query->the_post(); if( $my_query->is_author()){ // do something for author } endwhile; wp_reset_postdata();
  • 16. why we always needs to call wp_reset_query() wp_reset_postdata(); with query_posts() or WP_Query()
  • 17. because when we do this query_posts( 'cat=5'); while ( have_posts() ) : the_post(); //the_title(), the_ID(), the_permalink() etc.. endwhile; We have altered the main query...
  • 18. How? global $wp_query; //this is the main query object Do anyone know this? $wp_the_query So the real main query object $wp_the_query and $wp_query is the live copy of $wp_the_query
  • 19. it is something like $wp_the_query = new WP_Query(); $wp_query = &$wp_the_query;
  • 20. when we call query_posts(), it works like this function query_posts($query) { $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query($query); }
  • 21. and when we call wp_reset_query() function wp_reset_query() { $GLOBALS['wp_query'] = $GLOBALS['wp_the_query']; wp_reset_postdata(); }
  • 22.
  • 23. how many query(s) get called when we call WP_Query()? Is it running only one query with your passed arguments????
  • 24. it is running 4 queries 1. Select SQL_CALC_FOUND_ROWS....FROM wp_posts limit 0,10 2. Select FOUND_ROWS(); 3. Get all metadata attached to these posts. 4. Get all terms for these posts.
  • 25. off some arguments selectively new WP_Query( array( 'no_found_rows' => false, 'update_post_meta_cache' => false, 'update_post_term_cache' => false ) )
  • 26. what if I need to modify the main query only? Use pre_get_posts hook
  • 27. function exclude_category( $query ) { $query->set( 'cat', '-1,-1347' ); } add_action( 'pre_get_posts', 'exclude_category' );
  • 28. Now problem with this... it gets called for every post query get_posts() WP_Query() query_posts()
  • 29. what if I just need it for home page query? now $wp_the_query object will help function exclude_category( $query ) { global $wp_the_query; if( $wp_the_query == $query and $query->home()){ $query->set( 'cat', '-1,-1347' ); } } add_action( 'pre_get_posts', 'exclude_category' );
  • 30. After WordPress 3.3 we have an awesome function is_main_query()
  • 31. So rather than writing function exclude_category( $query ) { global $wp_the_query; //if( $wp_the_query == $query and $query->home()) if( $query->is_main_query() and $query->home()) { $query->set( 'cat', '-1,-1347' ); }
  • 32. Conclusion  Try to avoid using query_posts()  If query_posts() is used then reset it with wp_reset_query()  Use pre_get_posts hook to alter main query & use it with is_main_query() condition tag