SlideShare a Scribd company logo
1 of 53
Download to read offline
You Don’t Know Query

   WordPress London
   WordPress London
    May 16, 2012
Scott Cariss aka Brady
         Scott Cariss aka Brady
• Lead developer at Philosophy Design.
     dd l            hil    h     i

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

• WordPress plugin developer and enthusiast
  WordPress plugin developer and enthusiast

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

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

    return $wp_query >is_author();
    return $wp query‐>is author();
}
If you do: 
$my_query new WP Query( $query );
$my query = new WP_Query( $query ); 

You can do: 
while ( $my_query >have_posts( ) ) :
while ( $my query‐>have posts( ) ) :
  $my_query‐>the_post( ); endwhile;
wp_reset_postdata( ); 
But why do we call things like
     h d        ll hi     lik
wp_reset_postdata( ) and
 p_     _p         ()
wp_reset_query( )? 

What about using query_posts( )? 

How can you alter a query? What about
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.
Let's dig in
wp‐blog‐header.php
          wp blog header php
// Load the WordPress bootstrap require
//    d h      d        b              i
dirname( __FILE__ ) . '/wp‐load.php'; 
         ( __  __ )       p     p p




// Decide which template files to load
// Decide which template files to load
ABSPATH . WPINC . '/template‐loader.php'; 
Let s look in the bootstrap:
     Let’s look in the bootstrap:
$wp_the_query = new WP_Query();
$wp_query & $wp_the_query;
$wp query =& $wp the query;
Quick lesson on PHP references
    Quick lesson on PHP references
// References in PHP are a means to access the same variable content 
// R f        i PHP              t         th          i bl     t t
   by different names.

$a = 4;
$b =& $a;

// It means that $a and $b now point to the same content.

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

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

And a live copy of it is stored in
$wp_query
$wp query
wp‐blog‐header.php
          wp blog header php
// Load the WordPress bootstrap require
//    d h      d        b              i
dirname( __FILE__ ) . '/wp‐load.php'; 
         ( __  __ )       p     p p

// Do magic
// Do magic
wp();

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

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

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

WP::query_posts( )
{
   global $wp_the_query;
   $ p_
   $wp the_q y q y( $
            query‐>query( $this‐>query vars ); 
                                 q y_       );
} 
What do we get?
           What do we get?
SELECT SQL_CALC_FOUND_ROWS 
  wp_posts. FROM
  wp posts.* FROM
wp_posts WHERE 1=1 
  AND wp_posts.post_type = 'post‘
  AND wp_posts.post_status =  publish ORDER
  AND wp posts post status = 'publish' ORDER
BY wp_posts.post_date DESC LIMIT 0, 10 
wp‐blog‐header.php
          wp blog header php
// Load WordPress
//    d     d
dirname( __FILE__ ) . '/wp‐load.php'; 
        ( __   __ )      p      p p

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

// Load the theme.
// 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?
       Then why do we do this?
query_posts( 'author=5' );
           (' h       ')
g _
get_header( );
          ()

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

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

Two, this new one you’re
actually going to use.
actually going to use
* Actually, WP_Query doesn't run just one
query. It usually runs four. 
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?
2 How many posts exist?
     SELECT FOUND_ROWS() 
3. Pull down all metadata for these posts.
4. Pull down all terms for these posts. 
4 Pull down all terms for these posts
Instead of query_posts()?
       Instead of query posts()?
We can use this:

// In WP::parse_request()

$this >query_vars = apply_filters(  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;
}
Powerful, but lacks context.
     Powerful but lacks context
Problems:

1. Conditional tags don’t work yet.

2. Only works on the main query.
2 Only works on the main query

3. WP_Query is way cooler.
Introducing pre_get_posts
        Introducing pre get posts
class WP_Query
  l WP Q
{ 
   . . .
   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()!
      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?
               Still with us?
Good ‘cause here’s where things get hairy.
‘request’ fires for the main query only.
‘       ’ fi f h          i          l

‘pre_get_posts’ fires for every post query:

•   get_posts()
•   new WP_Query()
•   That random recent posts widget.
    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!
            Main query only!
function brady_alter_home( $query )
f      i b d l        h      ($     )
{
  if ( $query‐>is_home( ) &&
        $wp_the_query === $query ) 
        $wp the query === $query )
     $query‐>set( 'author', '‐5' );
}
add_action(  pre_get_posts
add action( 'pre get posts', 
  ‘brady_alter_home' );
Hmm. How does this work?
     Hmm How does this work?
$wp_the_query should never be modified. It 
                q y
 holds the main query, forever. 

$wp_query k
$         keeps a live reference to 
                  li     f
  $wp_the_query, unless you use query_posts(). 
query_posts( 'author=‐5' ); 
while ( have_posts( ) ) : 
while ( have posts( ) ) :
  the_post( );
endwhile;
wp_reset_query( ); 
wp reset query( );
class WP_Query
  l WP Q
{ 
   . . . 
   function &query_posts( $query )
   { 
       // Break the reference to $wp_the_query
       // Break the reference to $wp the query
       unset( $wp_query ); 
       $wp_query =& new WP_Query( $query ); 
       ...
   }
   ...
}
query_posts( 'author=‐5' ); 
while ( have_posts( ) ) : 
while ( have posts( ) ) :
  the_post( );
endwhile;
wp_reset_query( ); 
wp reset query( );
class WP_Query
class WP Query
{
   . . .
   function wp_reset_query( )
   f                           ()
   { 
       // Restore the reference to $wp_the_query
       unset( $wp_query );
       $wp_query =& $wp_the_query; 
       //
       // Reset the globals, too.
                    g      ,
       wp_reset_postdata( );
       . . . 
   }
   ....
}
Calling the_post( )? wp_reset_query( ) will reset 
  $wp_query and and the globals. 
      p_q y               g

Calling $my_query‐>the_post( )? 
C lli $             h         ( )?
  wp_reset_postdata( ) will reset the globals. 
Since WordPress 3.3!
         Since WordPress 3 3!
Rather than: 
$wp_the_query
$wp the query === $other_query_object
                  $other query object

You‘re able to call: 
$other_query_object >is_main_query( ) 
$other query object‐>is main query( )
Some Lessons
              Some Lessons
Every WP_Query object has methods that mimic 
      g                    g
  the global conditional tags.

The global conditional tags apply to $wp_query, 
Th l b l      di i   l         l     $
  the main or current query. 

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

Always check if you're modifying the main query 
Al       h k if     '    dif i    h    i
   using $query‐>is_main_query( ) 

$query === $wp_the_query b f
$          $   th        before 3.3
                                33
Thank you! Any questions?
     Thank you! Any questions?
Further in‐depth discussion on query_posts():
• @l3rady on Twitter.
  @l3rady on Twitter.
• Down the pub after presentations.

More Related Content

What's hot

DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginnersleo lapworth
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介Jace Ju
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 WorldFabien Potencier
 
Your code sucks, let's fix it! - php|tek13
Your code sucks, let's fix it! - php|tek13Your code sucks, let's fix it! - php|tek13
Your code sucks, let's fix it! - php|tek13Rafael Dohms
 
Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)Michael Schwern
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Kris Wallsmith
 
Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Goro Fuji
 
HTML Templates Using Clear Silver
HTML Templates Using Clear SilverHTML Templates Using Clear Silver
HTML Templates Using Clear SilverPaulWay
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixturesBill Chang
 

What's hot (20)

Lithium Best
Lithium Best Lithium Best
Lithium Best
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 
Your code sucks, let's fix it! - php|tek13
Your code sucks, let's fix it! - php|tek13Your code sucks, let's fix it! - php|tek13
Your code sucks, let's fix it! - php|tek13
 
Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)
 
Perl6 grammars
Perl6 grammarsPerl6 grammars
Perl6 grammars
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
 
Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11
 
HTML Templates Using Clear Silver
HTML Templates Using Clear SilverHTML Templates Using Clear Silver
HTML Templates Using Clear Silver
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 

Similar to WordPress London 16 May 2012 - You don’t know 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
 
Как получить чёрный пояс по 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
 
Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainDrewAPicture
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Yevhen Kotelnytskyi
 
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.noMorten Rand-Hendriksen
 
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
 
[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
 
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
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
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
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
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)Mike Schinkel
 
Apostrophe
ApostropheApostrophe
Apostrophetompunk
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress DeveloperJoey Kudish
 
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
 

Similar to WordPress London 16 May 2012 - You don’t know 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
 
Как получить чёрный пояс по 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
 
Getting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, Again
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
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
 
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
 
[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
 
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()
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
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
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
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)
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Apostrophe
ApostropheApostrophe
Apostrophe
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 

Recently uploaded

The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingSelcen Ozturkcan
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Recently uploaded (20)

The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

WordPress London 16 May 2012 - You don’t know query

  • 1. You Don’t Know Query WordPress London WordPress London May 16, 2012
  • 2. Scott Cariss aka Brady Scott Cariss aka Brady • Lead developer at Philosophy Design. dd l hil h i • Moderator at WordPress Answers  ( p (http://wordpress.stackexchange.com/) p g ) • WordPress plugin developer and enthusiast WordPress plugin developer and enthusiast scott@philosophydesign @ hil h d i @l3rady on Twitter
  • 5. Conditional Tags Conditional Tags is_author(), is_home(), etc.
  • 7. Ways to query Ways to query query_posts() new WP_Query() new WP Query() get_posts()
  • 8. The loop The loop if( have_posts() ) while( 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() $wp query‐>is author()
  • 11. function is_author() { global $wp_query; return $wp_query >is_author(); return $wp query‐>is author(); }
  • 12. If you do:  $my_query new WP Query( $query ); $my query = new WP_Query( $query );  You can do:  while ( $my_query >have_posts( ) ) : while ( $my query‐>have posts( ) ) : $my_query‐>the_post( ); endwhile; wp_reset_postdata( ); 
  • 13. But why do we call things like h d ll hi lik wp_reset_postdata( ) and p_ _p () wp_reset_query( )?  What about using query_posts( )?  How can you alter a query? What about How can you alter a query? What about the main query? 
  • 16. wp‐blog‐header.php wp blog header php // Load the WordPress bootstrap require // d h d b i dirname( __FILE__ ) . '/wp‐load.php';  ( __ __ ) p p p // Decide which template files to load // Decide which template files to load ABSPATH . WPINC . '/template‐loader.php'; 
  • 17. Let s look in the bootstrap: Let’s look in the bootstrap: $wp_the_query = new WP_Query(); $wp_query & $wp_the_query; $wp query =& $wp the query;
  • 18. Quick lesson on PHP references Quick lesson on PHP references // References in PHP are a means to access the same variable content  // R f i PHP t th i bl t t by different names. $a = 4; $b =& $a; // It means that $a and $b now point to the same content. $b = 2; $b 2 var_dump( $a ); // int(2) $a = 6; var_dump( $b ); // int(6) 
  • 20. wp‐blog‐header.php wp blog header php // Load the WordPress bootstrap require // d h d b i dirname( __FILE__ ) . '/wp‐load.php';  ( __ __ ) p p p // Do magic // Do magic wp(); // Decide which template files to load // Decide which template files to load ABSPATH . WPINC . '/template‐loader.php'; 
  • 21. What is that wp() call? What is that wp() call? function wp( $query_vars = '' ) { global $wp;  $wp >main( $query_vars $wp‐>main( $query vars ); } 
  • 23. In the bootstrap: In the bootstrap: $wp = new WP() So there’s a wp() function, and a WP class.
  • 24. class WP class WP { ... function main( ) f () {  $this‐>init( ); $this‐>parse_request( ); $this‐>send_headers( ); $ $this‐>query posts( ); q y_p ( ); $this‐>handle_404( ); $this‐>register_globals( );  } . . .  }
  • 25. class WP class WP { ... function main( ) f () {  $this‐>init( ); $this‐>parse_request( ); $this‐>send_headers( ); $ $this‐>query posts( ); q y_p ( ); $this‐>handle_404( ); $this‐>register_globals( );  } . . .  }
  • 26. WP::parse_request( )  WP t( ) Parses the URL using WP_Rewrite Sets up query variables for WP_Query WP::query_posts( ) { global $wp_the_query; $ p_ $wp the_q y q y( $ query‐>query( $this‐>query vars );  q y_ ); } 
  • 27. What do we get? What do we get? SELECT SQL_CALC_FOUND_ROWS  wp_posts. FROM wp posts.* FROM wp_posts WHERE 1=1  AND wp_posts.post_type = 'post‘ AND wp_posts.post_status =  publish ORDER AND wp posts post status = 'publish' ORDER BY wp_posts.post_date DESC LIMIT 0, 10 
  • 28. wp‐blog‐header.php wp blog header php // Load WordPress // d d dirname( __FILE__ ) . '/wp‐load.php';  ( __ __ ) p p p // Parse what to query, and query it.  // Parse what to query and query it wp();  // Load the theme. // Load the theme ABSPATH . WPINC . '/template‐loader.php'; 
  • 29. Before we get to the theme, we have  your posts. Are we clear so far?
  • 30. Then why do we do this? Then why do we do this? query_posts( 'author=5' ); (' h ') g _ get_header( ); () while( have_posts( ) ) :  while( have posts( ) ) : the_post( ); endwhile; get_footer( ); 
  • 31. That s running 2 queries! That’s running 2* queries! One, the query WordPress thought we wanted. thought we wanted. Two, this new one you’re actually going to use. actually going to use
  • 33. 1. Get me my posts: SELECT _ _ _ SQL_CALC_FOUND_ROWS … FROM wp_posts LIMIT 0, 10  2. How many posts exist? 2 How many posts exist? SELECT FOUND_ROWS()  3. Pull down all metadata for these posts. 4. Pull down all terms for these posts.  4 Pull down all terms for these posts
  • 34. Instead of query_posts()? Instead of query posts()? We can use this: // In WP::parse_request() $this >query_vars = apply_filters(  request $this‐>query vars = apply filters( 'request',  $this‐>query_vars ); 
  • 35. We can modify query variables in mid  air: function brady_filter_out_author( $qvs ) { if( ! Isset( $qvs[‘author’] ) ) $qvs[‘author’] = ‘‐5’; return $qvs; }
  • 36. Powerful, but lacks context. Powerful but lacks context Problems: 1. Conditional tags don’t work yet. 2. Only works on the main query. 2 Only works on the main query 3. WP_Query is way cooler.
  • 37. Introducing pre_get_posts Introducing pre get posts class WP_Query l WP Q {  . . . function &get_posts() { {  $this‐>parse_query();  // OMG! Conditional tags are available!! do_action_ref_array( 'pre_get_posts', array( &$this ) );  } . . .  }
  • 38. Lets kill off query_posts()! 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' ); 
  • 39. Still with us? Still with us? Good ‘cause here’s where things get hairy.
  • 40. ‘request’ fires for the main query only. ‘ ’ fi f h i l ‘pre_get_posts’ fires for every post query: • get_posts() • new WP_Query() • That random recent posts widget. That random recent posts widget • Everything.
  • 42. $wp_the_query makes a triumphant return.
  • 43. Main query only! Main query only! function brady_alter_home( $query ) f i b d l h ($ ) { if ( $query‐>is_home( ) && $wp_the_query === $query )  $wp the query === $query ) $query‐>set( 'author', '‐5' ); } add_action(  pre_get_posts add action( 'pre get posts',  ‘brady_alter_home' );
  • 44. Hmm. How does this work? Hmm How does this work? $wp_the_query should never be modified. It  q y holds the main query, forever.  $wp_query k $ keeps a live reference to  li f $wp_the_query, unless you use query_posts(). 
  • 45. query_posts( 'author=‐5' );  while ( have_posts( ) ) :  while ( have posts( ) ) : the_post( ); endwhile; wp_reset_query( );  wp reset query( );
  • 46. class WP_Query l WP Q {  . . .  function &query_posts( $query ) {  // Break the reference to $wp_the_query // Break the reference to $wp the query unset( $wp_query );  $wp_query =& new WP_Query( $query );  ... } ... }
  • 47. query_posts( 'author=‐5' );  while ( have_posts( ) ) :  while ( have posts( ) ) : the_post( ); endwhile; wp_reset_query( );  wp reset query( );
  • 48. class WP_Query class WP Query { . . . function wp_reset_query( ) f () {  // Restore the reference to $wp_the_query unset( $wp_query ); $wp_query =& $wp_the_query;  // // Reset the globals, too. g , wp_reset_postdata( ); . . .  } .... }
  • 49. Calling the_post( )? wp_reset_query( ) will reset  $wp_query and and the globals.  p_q y g Calling $my_query‐>the_post( )?  C lli $ h ( )? wp_reset_postdata( ) will reset the globals. 
  • 50. Since WordPress 3.3! Since WordPress 3 3! Rather than:  $wp_the_query $wp the query === $other_query_object $other query object You‘re able to call:  $other_query_object >is_main_query( )  $other query object‐>is main query( )
  • 51. Some Lessons Some Lessons Every WP_Query object has methods that mimic  g g the global conditional tags. The global conditional tags apply to $wp_query,  Th l b l di i l l $ the main or current query.  $wp_query i l $ is always the main query, unless you  th i l use query_posts( ). Restore it with  wp_reset_query( ).
  • 52. And finally And finally request is a nice hook. pre_get_posts is more  p powerful and flexible. Just use it properly.  p p y Always check if you're modifying the main query  Al h k if ' dif i h i using $query‐>is_main_query( )  $query === $wp_the_query b f $ $ th before 3.3 33
  • 53. Thank you! Any questions? Thank you! Any questions? Further in‐depth discussion on query_posts(): • @l3rady on Twitter. @l3rady on Twitter. • Down the pub after presentations.