The Query the Whole Query and Nothing but the Query

Chris Olbekson
Chris OlbeksonWordPress Developer & Consultant at X-Team
WordCamp Austin 2012
Chris Olbekson

WordPress Consultant
C3M Digital


@Chris_Olbekson on Twitter
chris@c3mdigital.com



WordCamp Austin 2012
The Query, The Whole
Query, & Nothing But
     $the_query
What is the query?
What is the query?
     The Loop
What is the query?
           The Loop
  while( have_posts() ): the_post();
    the_content();
  endwhile;
What is the query?
   WP_Query class
What is the query?
   $wp_query object
class WP_Query
$wp_query object


The WP Class gives the $wp_query object
information that defines the current
request.
class WP_Query
            $wp_query object

The WP Class gives the $wp_query object
information that defines the current
request.

$wp_query determines the query based on
that information and fetches the
requested posts
class WP_Query

class WP {

   function main() {
       $this->init();
       $this->parse_request();
       $this->query_posts();
       $this->handle_404();
       $this->register_globals()




      $wp_query object
class WP_Query

                   Properties
$query, $query_vars, $posts, $post_count,
$current_post, $queried_object_id, etc...
 Booleans: is_single(), is_category(), is_paged(),
etc...
class WP_Query

                   Methods

init(), parse_query(), set( $query_var, $value ),
have_posts(), rewind_posts() etc...
class WP_Query

Interacting with WP_Query
class WP_Query

      Interacting with WP_Query

Before the loop
Altering the query, filters
class WP_Query

      Interacting with WP_Query

During the loop
Conditionals and template tags,
secondary queries, get_sidebar(), more
secondary queries, get_footer().
How do we Query?
How do we Query?
query_posts() alters the main query
How do we Query?
query_posts() alters the main query

new WP_Query() use for secondary queries
How do we Query?
query_posts() alters the main query

new WP_Query() use for secondary queries
 WP_Query - returns an array of post objects
How do we Query?
query_posts() alters the main query

new WP_Query() use for secondary queries
 WP_Query - returns an array of post objects

get_posts() use for secondary queries
How do we Query?
query_posts() alters the main query

new WP_Query() use for secondary queries
 WP_Query - returns an array of post objects

get_posts() use for secondary queries
 get_posts() - wrapper for a separate instance of WP_Query
 returns an array of post objects
How do we Query?
query_posts() alters the main query

new WP_Query() use for secondary queries
 WP_Query - returns an array of post objects

get_posts() use for secondary queries
 get_posts() - wrapper for a separate instance of WP_Query
 returns an array of post objects


$wpdb->roll your own
How do we Query?
query_posts() alters the main query

new WP_Query() use for secondary queries
 WP_Query - returns an array of post objects

get_posts() use for secondary queries
 get_posts() - wrapper for a separate instance of WP_Query
 returns an array of post objects


$wpdb->roll your own
 $wpdb uses the wpdb class to execute any SQL query on the
 WordPress database
Secondary Loops
Secondary Loops
       new WP_Query()

$my_query = new WP_Query();
while( $my_query->have_posts() ):
    $my_query->the_post();
    // do stuff
 endwhile;
Secondary Loops
            get_posts()
get_posts() uses the WP_Query class to
fetch an array of post objects


$post->post_content, $post->post_title
etc...
Secondary Loops
                        get_posts()

$post = get_posts( array(
    ‘posts_per_page’ => 7
! ! ‘cat’ => -3,
));

!       foreach( $posts as $post ) {
            echo $post->post_title;
            echo apply_filters( ‘the_content’, $post->post_content );
    }
Secondary Loops
                    get_posts()

$post = get_posts( array(
    ‘posts_per_page’ => 7
! ! ‘cat’ => -3,
));


/**
 *
 * To make post template tags ie: the_content()
 * available when using get_posts() call the
 * internal function setup_postdata() with the
 * the $post array as its argument
 *
 */
Secondary Loops
                    get_posts()

$post = get_posts( array(
    ‘posts_per_page’ => 7
! ! ‘cat’ => -3,
));


foreach( $posts as $post ) {
!     setup_postdata( $post );
      the_title();
      the_content();
    }
Secondary Loops
                    get_posts()

$post = get_posts( array(
    ‘posts_per_page’ => 7
! ! ‘cat’ => -3,
));



**/
 *
 * After looping through a separate query,
 * wp_reset_postdata() restores the $post global
 * to the current post in the main query
 *
 */
Secondary Loops
                    get_posts()

$post = get_posts( array(
   ‘posts_per_page’ => 7
! ! ‘cat’ => -3,
));

foreach( $posts as $post ) {
!     setup_postdata( $post );
      the_title();
      the_content();
    }
    wp_reset_postdata();
query_posts()
query_posts()

query_posts() sets up The Loop with
query parameters. It also overrides the
current WordPress Loop.
query_posts()

query_posts( array(
   ‘posts_per_page’ => 7
! ! ‘cat’ => -3,
));

if ( have_posts() ) : while ( have_posts() : the_post();
    the_title();
    the_content();
endwhile; endif;
query_posts()

query_posts( array(
   ‘posts_per_page’ => 7
! ! ‘cat’ => -3,
));

**/
 * If you use query_posts() you HAVE to use
 * wp_reset_query() to restore the $post globals
 *
 */
query_posts()

query_posts( array(
   ‘posts_per_page’ => 7
! ! ‘cat’ => -3,
));

if ( have_posts() ) : while ( have_posts() : the_post();
    the_title();
    the_content();
endwhile; endif; wp_reset_query();
query_posts()
      query_posts() alters destroys the
         global $wp_query variables

/**
 *
 * This will cause WordPress to run the query it
 * thought you wanted and the one you’re actually going
 * to use.
 *
 * breaks widgets
 * pagination breaks
 * conditional tags will not work
 * and more...
 *
 */
When should we use
  query_posts()?
query_posts()

The Problem with query_posts() is that it
is always a secondary loop that tries to
be the main one and fails miserably.
When should we use
  query_posts()?
When should we use
  query_posts()?
NEVER USE query_posts()
When should we use
  query_posts()?
NEVER USE query_posts()

     query_posts()
What if I want to alter
       the query?
pre_get_posts()
pre_get_posts()

pre_get_posts fires every time WordPress
fetches posts from the database.

nav menus, new wp_query, query_posts,
get_posts, that slider plugin your client
installed, everything.
What if I only want to
alter the main query?
is_main_query()
is_main_query()

function alter_query( $query ) {
! if ( $query->is_main_query() && $query->is_home() )
! !     $query->set( ‘cat’, ‘-3’ );
}
add_action( ‘pre_get_posts’, ‘alter_query’ );
What happens when we
    run a query?
What happens when we
     run a query?

WordPress actually runs 4 SQL queries
      every time a query is run
$my_query = new WP_Query();
 while( $my_query->have_posts() ):
   $my_query->the_post();
$my_query = new WP_Query();
  while( $my_query->have_posts() ):
     $my_query->the_post();
1)Gets the posts:
  SELECT SQL_CALC_FOUND_ROWS...
  FROM wp_post LIMIT 0, 10
$my_query = new WP_Query();
  while( $my_query->have_posts() ):
     $my_query->the_post();
1)Gets the posts:
  SELECT SQL_CALC_FOUND_ROWS...
  FROM wp_post LIMIT 0, 10

2)Counts the posts for pagination:
  SELECT FOUND_ROWS()
$my_query = new WP_Query();
  while( $my_query->have_posts() ):
     $my_query->the_post();
1)Gets the posts:
  SELECT SQL_CALC_FOUND_ROWS...
  FROM wp_post LIMIT 0, 10

2)Counts the posts for pagination:
  SELECT FOUND_ROWS()

3)Gets all the metadata:
  SELECT post_id, meta_key, meta_value FROM
  wp_postmeta WHERE post_id IN...
$my_query = new WP_Query();
  while( $my_query->have_posts() ):
     $my_query->the_post();
1)Gets the posts:
  SELECT SQL_CALC_FOUND_ROWS...
  FROM wp_post LIMIT 0, 10

2)Counts the posts for pagination:
  SELECT FOUND_ROWS()

3)Gets all the metadata:
  SELECT post_id, meta_key, meta_value FROM
  wp_postmeta WHERE post_id IN...

4)Gets all the terms
 SELECT… AS… INNER JOIN wp_term_taxonomy
 AS... INNER JOIN wp_term_relationships
 AS... ON... IN...
What if I don’t need
pagination, meta, or
       terms?
What if I don’t need
pagination, meta, or
       terms?
You can selectively turn these off
What if I don’t need
pagination, meta, or
       terms?
  You can selectively turn these off

$my_query = new WP_Query( array(
          ‘no_found_rows’ = true,
          ‘update_post_meta_cache’ => false,
          ‘update_post_term_cache’ => false,
          ) );
<review>
$wp_query is always the main query
if you use query_posts(), $wp_query now holds the query
you just created.
<review>
$wp_query is always the main query
if you use query_posts(), $wp_query now holds the query
you just created.

Use pre_get_posts() when you need to alter the main query.
It’s cleaner the “right” way to do it and your clients and
fellow developers will love you.
<review>
$wp_query is always the main query
if you use query_posts(), $wp_query now holds the query
you just created.

Use pre_get_posts() when you need to alter the main query.
It’s cleaner the “right” way to do it and your clients and
fellow developers will love you.

For secondary queries - custom sliders, sidebars, etc...
use get_posts() or create a new WP_Query
<review>
$wp_query is always the main query
if you use query_posts(), $wp_query now holds the query
you just created.

Use pre_get_posts() when you need to alter the main query.
It’s cleaner the “right” way to do it and your clients and
fellow developers will love you.

For secondary queries - custom sliders, sidebars, etc...
use get_posts() or create a new WP_Query

If you call the_post(), or set_up_postdata() use
wp_reset_postdata(). If you have to use query_posts() use
wp_reset_query().
</review>
questions?
1 of 66

Recommended

MTDDC 2010.2.5 Tokyo - Brand new API by
MTDDC 2010.2.5 Tokyo - Brand new APIMTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APISix Apart KK
2.2K views110 slides
Getting Creative with WordPress Queries by
Getting Creative with WordPress QueriesGetting Creative with WordPress Queries
Getting Creative with WordPress QueriesDrewAPicture
4.8K views41 slides
Getting Creative with WordPress Queries, Again by
Getting Creative with WordPress Queries, AgainGetting Creative with WordPress Queries, Again
Getting Creative with WordPress Queries, AgainDrewAPicture
515 views50 slides
Doctrine 2 by
Doctrine 2Doctrine 2
Doctrine 2zfconfua
1.7K views40 slides
Intro programacion funcional by
Intro programacion funcionalIntro programacion funcional
Intro programacion funcionalNSCoder Mexico
306 views29 slides
Caching and Scaling WordPress using Fragment Caching by
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingErick Hitter
3.1K views26 slides

More Related Content

What's hot

50 Laravel Tricks in 50 Minutes by
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurtaliev
1.7K views83 slides
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway by
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway ichikaway
7.4K views76 slides
The Origin of Lithium by
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
8.4K views22 slides
How else can you write the code in PHP? by
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?Maksym Hopei
171 views32 slides
Как получить чёрный пояс по WordPress? by
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Yevhen Kotelnytskyi
1.6K views62 slides
Как получить чёрный пояс по WordPress? v2.0 by
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Yevhen Kotelnytskyi
738 views62 slides

What's hot(20)

50 Laravel Tricks in 50 Minutes by Azim Kurtaliev
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Azim Kurtaliev1.7K views
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway by ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
ichikaway7.4K views
The Origin of Lithium by Nate Abele
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
Nate Abele8.4K views
How else can you write the code in PHP? by Maksym Hopei
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?
Maksym Hopei171 views
Как получить чёрный пояс по WordPress? by Yevhen Kotelnytskyi
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
Yevhen Kotelnytskyi1.6K views
Как получить чёрный пояс по WordPress? v2.0 by Yevhen Kotelnytskyi
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
The Zen of Lithium by Nate Abele
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele2.6K views
PHP 5.3 and Lithium: the most rad php framework by G Woo
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
G Woo5.9K views
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module by Erich Beyrent
Digital Mayflower - Data Pilgrimage with the Drupal Migrate ModuleDigital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Erich Beyrent490 views
Lithium: The Framework for People Who Hate Frameworks by Nate Abele
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele12.2K views
購物車程式架構簡介 by Jace Ju
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
Jace Ju19.7K views
The History of PHPersistence by Hugo Hamon
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Hugo Hamon2.3K views
Database Design Patterns by Hugo Hamon
Database Design PatternsDatabase Design Patterns
Database Design Patterns
Hugo Hamon11.4K views
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014 by Cliff Seal
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Cliff Seal1.6K views
Phactory by chriskite
PhactoryPhactory
Phactory
chriskite1.3K views
Building Lithium Apps by Nate Abele
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele5.7K views
Building a Pluggable Plugin by Brandon Dove
Building a Pluggable PluginBuilding a Pluggable Plugin
Building a Pluggable Plugin
Brandon Dove1.9K views

Similar to The Query the Whole Query and Nothing but the Query

You Don't Know Query - WordCamp Portland 2011 by
You Don't Know Query - WordCamp Portland 2011You Don't Know Query - WordCamp Portland 2011
You Don't Know Query - WordCamp Portland 2011andrewnacin
11.1K views61 slides
Wp query by
Wp queryWp query
Wp querySavita Soni
6.6K views33 slides
You don’t know query - WordCamp UK Edinburgh 2012 by
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
978 views53 slides
WordPress London 16 May 2012 - You don’t know query by
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
1.1K views53 slides
You Don't Know Query (WordCamp Netherlands 2012) by
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
62.3K views69 slides
WordPress Queries - the right way by
WordPress Queries - the right wayWordPress Queries - the right way
WordPress Queries - the right wayAnthony Hortin
3.8K views49 slides

Similar to The Query the Whole Query and Nothing but the Query(20)

You Don't Know Query - WordCamp Portland 2011 by andrewnacin
You Don't Know Query - WordCamp Portland 2011You Don't Know Query - WordCamp Portland 2011
You Don't Know Query - WordCamp Portland 2011
andrewnacin11.1K views
You don’t know query - WordCamp UK Edinburgh 2012 by l3rady
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
l3rady978 views
WordPress London 16 May 2012 - You don’t know query by l3rady
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
l3rady1.1K views
You Don't Know Query (WordCamp Netherlands 2012) by andrewnacin
You Don't Know Query (WordCamp Netherlands 2012)You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)
andrewnacin62.3K views
WordPress Queries - the right way by Anthony Hortin
WordPress Queries - the right wayWordPress Queries - the right way
WordPress Queries - the right way
Anthony Hortin3.8K views
WP_Query, pre_get_posts, and eliminating query_posts() by Erick Hitter
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 Hitter8.3K views
[WLDN] Supercharging word press development in 2018 by Adam Tomat
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
Adam Tomat291 views
Wordpress multiple loops by Roman Rus
Wordpress multiple loopsWordpress multiple loops
Wordpress multiple loops
Roman Rus1.5K views
WordPress as an application framework by Dustin Filippini
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
Dustin Filippini416 views
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP by Vineet Kumar Saini
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
Vineet Kumar Saini2.3K views
Working with WP_Query in WordPress by topher1kenobe
Working with WP_Query in WordPressWorking with WP_Query in WordPress
Working with WP_Query in WordPress
topher1kenobe1.7K views
Getting to The Loop - London Wordpress Meetup July 28th by Chris Adams
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
Chris Adams953 views
Apostrophe by tompunk
ApostropheApostrophe
Apostrophe
tompunk5.4K views
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014 by Cliff Seal
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Cliff Seal5K views

More from Chris Olbekson

Magical WordPress Development with Vagrant by
Magical WordPress Development with VagrantMagical WordPress Development with Vagrant
Magical WordPress Development with VagrantChris Olbekson
3.4K views29 slides
Managing themes and server environments with extensible configuration arrays by
Managing themes and server environments with extensible configuration arraysManaging themes and server environments with extensible configuration arrays
Managing themes and server environments with extensible configuration arraysChris Olbekson
650 views25 slides
WordPress Houston Meetup - Using WordPress as a CMS by
WordPress Houston Meetup - Using WordPress as a CMSWordPress Houston Meetup - Using WordPress as a CMS
WordPress Houston Meetup - Using WordPress as a CMSChris Olbekson
1.1K views18 slides
Cognac gautier presentation by
Cognac gautier   presentationCognac gautier   presentation
Cognac gautier presentationChris Olbekson
1.9K views38 slides
Theme frameworks & child themes by
Theme frameworks & child themesTheme frameworks & child themes
Theme frameworks & child themesChris Olbekson
812 views15 slides
Optimizing WordPress for Performance - WordCamp Houston by
Optimizing WordPress for Performance - WordCamp HoustonOptimizing WordPress for Performance - WordCamp Houston
Optimizing WordPress for Performance - WordCamp HoustonChris Olbekson
605 views28 slides

More from Chris Olbekson(6)

Magical WordPress Development with Vagrant by Chris Olbekson
Magical WordPress Development with VagrantMagical WordPress Development with Vagrant
Magical WordPress Development with Vagrant
Chris Olbekson3.4K views
Managing themes and server environments with extensible configuration arrays by Chris Olbekson
Managing themes and server environments with extensible configuration arraysManaging themes and server environments with extensible configuration arrays
Managing themes and server environments with extensible configuration arrays
Chris Olbekson650 views
WordPress Houston Meetup - Using WordPress as a CMS by Chris Olbekson
WordPress Houston Meetup - Using WordPress as a CMSWordPress Houston Meetup - Using WordPress as a CMS
WordPress Houston Meetup - Using WordPress as a CMS
Chris Olbekson1.1K views
Cognac gautier presentation by Chris Olbekson
Cognac gautier   presentationCognac gautier   presentation
Cognac gautier presentation
Chris Olbekson1.9K views
Theme frameworks & child themes by Chris Olbekson
Theme frameworks & child themesTheme frameworks & child themes
Theme frameworks & child themes
Chris Olbekson812 views
Optimizing WordPress for Performance - WordCamp Houston by Chris Olbekson
Optimizing WordPress for Performance - WordCamp HoustonOptimizing WordPress for Performance - WordCamp Houston
Optimizing WordPress for Performance - WordCamp Houston
Chris Olbekson605 views

Recently uploaded

Scaling Knowledge Graph Architectures with AI by
Scaling Knowledge Graph Architectures with AIScaling Knowledge Graph Architectures with AI
Scaling Knowledge Graph Architectures with AIEnterprise Knowledge
50 views15 slides
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveNetwork Automation Forum
43 views35 slides
Network Source of Truth and Infrastructure as Code revisited by
Network Source of Truth and Infrastructure as Code revisitedNetwork Source of Truth and Infrastructure as Code revisited
Network Source of Truth and Infrastructure as Code revisitedNetwork Automation Forum
32 views45 slides
"Node.js Development in 2024: trends and tools", Nikita Galkin by
"Node.js Development in 2024: trends and tools", Nikita Galkin "Node.js Development in 2024: trends and tools", Nikita Galkin
"Node.js Development in 2024: trends and tools", Nikita Galkin Fwdays
17 views38 slides
Design Driven Network Assurance by
Design Driven Network AssuranceDesign Driven Network Assurance
Design Driven Network AssuranceNetwork Automation Forum
19 views42 slides
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...James Anderson
126 views32 slides

Recently uploaded(20)

Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
"Node.js Development in 2024: trends and tools", Nikita Galkin by Fwdays
"Node.js Development in 2024: trends and tools", Nikita Galkin "Node.js Development in 2024: trends and tools", Nikita Galkin
"Node.js Development in 2024: trends and tools", Nikita Galkin
Fwdays17 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson126 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely29 views
Future of AR - Facebook Presentation by Rob McCarty
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
Rob McCarty22 views
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays33 views
2024: A Travel Odyssey The Role of Generative AI in the Tourism Universe by Simone Puorto
2024: A Travel Odyssey The Role of Generative AI in the Tourism Universe2024: A Travel Odyssey The Role of Generative AI in the Tourism Universe
2024: A Travel Odyssey The Role of Generative AI in the Tourism Universe
Simone Puorto13 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker48 views
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by Dr. Jimmy Schwarzkopf
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2218 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva

The Query the Whole Query and Nothing but the Query

  • 2. Chris Olbekson WordPress Consultant C3M Digital @Chris_Olbekson on Twitter chris@c3mdigital.com WordCamp Austin 2012
  • 3. The Query, The Whole Query, & Nothing But $the_query
  • 4. What is the query?
  • 5. What is the query? The Loop
  • 6. What is the query? The Loop while( have_posts() ): the_post(); the_content(); endwhile;
  • 7. What is the query? WP_Query class
  • 8. What is the query? $wp_query object
  • 10. $wp_query object The WP Class gives the $wp_query object information that defines the current request.
  • 11. class WP_Query $wp_query object The WP Class gives the $wp_query object information that defines the current request. $wp_query determines the query based on that information and fetches the requested posts
  • 12. class WP_Query class WP { function main() { $this->init(); $this->parse_request(); $this->query_posts(); $this->handle_404(); $this->register_globals() $wp_query object
  • 13. class WP_Query Properties $query, $query_vars, $posts, $post_count, $current_post, $queried_object_id, etc... Booleans: is_single(), is_category(), is_paged(), etc...
  • 14. class WP_Query Methods init(), parse_query(), set( $query_var, $value ), have_posts(), rewind_posts() etc...
  • 16. class WP_Query Interacting with WP_Query Before the loop Altering the query, filters
  • 17. class WP_Query Interacting with WP_Query During the loop Conditionals and template tags, secondary queries, get_sidebar(), more secondary queries, get_footer().
  • 18. How do we Query?
  • 19. How do we Query? query_posts() alters the main query
  • 20. How do we Query? query_posts() alters the main query new WP_Query() use for secondary queries
  • 21. How do we Query? query_posts() alters the main query new WP_Query() use for secondary queries WP_Query - returns an array of post objects
  • 22. How do we Query? query_posts() alters the main query new WP_Query() use for secondary queries WP_Query - returns an array of post objects get_posts() use for secondary queries
  • 23. How do we Query? query_posts() alters the main query new WP_Query() use for secondary queries WP_Query - returns an array of post objects get_posts() use for secondary queries get_posts() - wrapper for a separate instance of WP_Query returns an array of post objects
  • 24. How do we Query? query_posts() alters the main query new WP_Query() use for secondary queries WP_Query - returns an array of post objects get_posts() use for secondary queries get_posts() - wrapper for a separate instance of WP_Query returns an array of post objects $wpdb->roll your own
  • 25. How do we Query? query_posts() alters the main query new WP_Query() use for secondary queries WP_Query - returns an array of post objects get_posts() use for secondary queries get_posts() - wrapper for a separate instance of WP_Query returns an array of post objects $wpdb->roll your own $wpdb uses the wpdb class to execute any SQL query on the WordPress database
  • 27. Secondary Loops new WP_Query() $my_query = new WP_Query(); while( $my_query->have_posts() ): $my_query->the_post(); // do stuff endwhile;
  • 28. Secondary Loops get_posts() get_posts() uses the WP_Query class to fetch an array of post objects $post->post_content, $post->post_title etc...
  • 29. Secondary Loops get_posts() $post = get_posts( array( ‘posts_per_page’ => 7 ! ! ‘cat’ => -3, )); ! foreach( $posts as $post ) { echo $post->post_title; echo apply_filters( ‘the_content’, $post->post_content ); }
  • 30. Secondary Loops get_posts() $post = get_posts( array( ‘posts_per_page’ => 7 ! ! ‘cat’ => -3, )); /** * * To make post template tags ie: the_content() * available when using get_posts() call the * internal function setup_postdata() with the * the $post array as its argument * */
  • 31. Secondary Loops get_posts() $post = get_posts( array( ‘posts_per_page’ => 7 ! ! ‘cat’ => -3, )); foreach( $posts as $post ) { ! setup_postdata( $post ); the_title(); the_content(); }
  • 32. Secondary Loops get_posts() $post = get_posts( array( ‘posts_per_page’ => 7 ! ! ‘cat’ => -3, )); **/ * * After looping through a separate query, * wp_reset_postdata() restores the $post global * to the current post in the main query * */
  • 33. Secondary Loops get_posts() $post = get_posts( array( ‘posts_per_page’ => 7 ! ! ‘cat’ => -3, )); foreach( $posts as $post ) { ! setup_postdata( $post ); the_title(); the_content(); } wp_reset_postdata();
  • 35. query_posts() query_posts() sets up The Loop with query parameters. It also overrides the current WordPress Loop.
  • 36. query_posts() query_posts( array( ‘posts_per_page’ => 7 ! ! ‘cat’ => -3, )); if ( have_posts() ) : while ( have_posts() : the_post(); the_title(); the_content(); endwhile; endif;
  • 37. query_posts() query_posts( array( ‘posts_per_page’ => 7 ! ! ‘cat’ => -3, )); **/ * If you use query_posts() you HAVE to use * wp_reset_query() to restore the $post globals * */
  • 38. query_posts() query_posts( array( ‘posts_per_page’ => 7 ! ! ‘cat’ => -3, )); if ( have_posts() ) : while ( have_posts() : the_post(); the_title(); the_content(); endwhile; endif; wp_reset_query();
  • 39. query_posts() query_posts() alters destroys the global $wp_query variables /** * * This will cause WordPress to run the query it * thought you wanted and the one you’re actually going * to use. * * breaks widgets * pagination breaks * conditional tags will not work * and more... * */
  • 40. When should we use query_posts()?
  • 41. query_posts() The Problem with query_posts() is that it is always a secondary loop that tries to be the main one and fails miserably.
  • 42. When should we use query_posts()?
  • 43. When should we use query_posts()? NEVER USE query_posts()
  • 44. When should we use query_posts()? NEVER USE query_posts() query_posts()
  • 45. What if I want to alter the query?
  • 47. pre_get_posts() pre_get_posts fires every time WordPress fetches posts from the database. nav menus, new wp_query, query_posts, get_posts, that slider plugin your client installed, everything.
  • 48. What if I only want to alter the main query?
  • 50. is_main_query() function alter_query( $query ) { ! if ( $query->is_main_query() && $query->is_home() ) ! ! $query->set( ‘cat’, ‘-3’ ); } add_action( ‘pre_get_posts’, ‘alter_query’ );
  • 51. What happens when we run a query?
  • 52. What happens when we run a query? WordPress actually runs 4 SQL queries every time a query is run
  • 53. $my_query = new WP_Query(); while( $my_query->have_posts() ): $my_query->the_post();
  • 54. $my_query = new WP_Query(); while( $my_query->have_posts() ): $my_query->the_post(); 1)Gets the posts: SELECT SQL_CALC_FOUND_ROWS... FROM wp_post LIMIT 0, 10
  • 55. $my_query = new WP_Query(); while( $my_query->have_posts() ): $my_query->the_post(); 1)Gets the posts: SELECT SQL_CALC_FOUND_ROWS... FROM wp_post LIMIT 0, 10 2)Counts the posts for pagination: SELECT FOUND_ROWS()
  • 56. $my_query = new WP_Query(); while( $my_query->have_posts() ): $my_query->the_post(); 1)Gets the posts: SELECT SQL_CALC_FOUND_ROWS... FROM wp_post LIMIT 0, 10 2)Counts the posts for pagination: SELECT FOUND_ROWS() 3)Gets all the metadata: SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id IN...
  • 57. $my_query = new WP_Query(); while( $my_query->have_posts() ): $my_query->the_post(); 1)Gets the posts: SELECT SQL_CALC_FOUND_ROWS... FROM wp_post LIMIT 0, 10 2)Counts the posts for pagination: SELECT FOUND_ROWS() 3)Gets all the metadata: SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id IN... 4)Gets all the terms SELECT… AS… INNER JOIN wp_term_taxonomy AS... INNER JOIN wp_term_relationships AS... ON... IN...
  • 58. What if I don’t need pagination, meta, or terms?
  • 59. What if I don’t need pagination, meta, or terms? You can selectively turn these off
  • 60. What if I don’t need pagination, meta, or terms? You can selectively turn these off $my_query = new WP_Query( array( ‘no_found_rows’ = true, ‘update_post_meta_cache’ => false, ‘update_post_term_cache’ => false, ) );
  • 61. <review> $wp_query is always the main query if you use query_posts(), $wp_query now holds the query you just created.
  • 62. <review> $wp_query is always the main query if you use query_posts(), $wp_query now holds the query you just created. Use pre_get_posts() when you need to alter the main query. It’s cleaner the “right” way to do it and your clients and fellow developers will love you.
  • 63. <review> $wp_query is always the main query if you use query_posts(), $wp_query now holds the query you just created. Use pre_get_posts() when you need to alter the main query. It’s cleaner the “right” way to do it and your clients and fellow developers will love you. For secondary queries - custom sliders, sidebars, etc... use get_posts() or create a new WP_Query
  • 64. <review> $wp_query is always the main query if you use query_posts(), $wp_query now holds the query you just created. Use pre_get_posts() when you need to alter the main query. It’s cleaner the “right” way to do it and your clients and fellow developers will love you. For secondary queries - custom sliders, sidebars, etc... use get_posts() or create a new WP_Query If you call the_post(), or set_up_postdata() use wp_reset_postdata(). If you have to use query_posts() use wp_reset_query().

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. WP class in gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  10. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  11. \n
  12. WP::parse_request()\n- Parses the URL using WP_Rewrite\n- Sets up query variables for WP_Query\n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  19. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  20. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  21. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  22. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  23. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  24. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\n
  25. WP_Query is a class defined in wp-includes/query.php that deals with the intricacies of a request to a WordPress blog. The wp-blog-header.php (or the WP class in Version 2.0) gives the $wp_query object information defining the current request, and then $wp_query determines what type of query it&apos;s dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.\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
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n