SlideShare a Scribd company logo
1 of 28
Download to read offline
FUN WITH
 WP_QUERY
             Erick Hitter
              @ethitter

Lead WordPress Developer at Oomph, Inc.
     WordPress 3.3 Core Contributor
      WordCamp Boston Organizer
            Plugin Author
WHAT IS WP_QUERY?
WordPress class defined in wp-includes/query.php.
Responsible for majority of post-type retrieval from database.

Any front-end request made to WordPress is fulfilled by
WP_Query in what I refer to as the main query.

Used extensively by WordPress but also available to developers.
USING WP_QUERY
Most often, this is done in "The Loop" to use the results from the
main query.
<?php
        if ( have_posts() ) {
                while( have_posts() ) {
                        the_post();
                }
        }
?>
USING WP_QUERY: NEW WP_QUERY();
<?php
           $queried_posts = new WP_Query();

           if ( $queried_posts->have_posts() ) {
                   while( $queried_posts->have_posts() ) {
                           $queried_posts->the_post();
                           //Use functions such as the_title() and the_content() here.
                   }
           }

           wp_reset_query();
           wp_reset_postdata();
?>


     Creates a new object of the type WP_Query, setting up another instance of The Loop.
     wp_reset_query() and wp_reset_postdata() are necessary to restore the main WordPress
     query. More on this later.
     Best used whenever Template Tags are needed.
USING WP_QUERY: GET_POSTS();
<?php
           $queried_posts = get_posts();

           foreach( $queried_posts as $queried_post ) {
                   setup_postdata( $queried_post );
           }

           wp_reset_postdata();
?>


     get_posts() generates an array of post objects that match the query parameters.
     setup_postdata() and wp_reset_postdata() can be used if Template Tags, such as
     the_title(), are needed.
     Best used when Template Tags aren't needed or post data will be repurposed, such as generating an
     array of post IDs.
RESETTING QUERY AND
POSTDATA
After using new WP_Query(), calling wp_reset_query() and wp_reset_postdata() restores
the original query and postdata.
After using setup_postdata(), calling wp_reset_postdata() restores the post.
Calling the two reset functions ensures that the Conditional Tags operate as expected and balance of
page renders properly.
QUERY BASICS
Can pass parameters as an array or query string.
<?php
          $foo = new WP_Query( array( 'posts_per_page' => 5 ) );
          $bar = new WP_Query( 'posts_per_page=5' );
?>


Array format is more flexible and necessary for queries such as:
    'post__not_in'
     'tax_query'
     'meta_query'

Query string format is parsed into an array by the WP_Query class.
QUERY PARAMETERS
Extensive list in the Codex at http://codex.wordpress.org/Class_Reference/WP_Query#Parameters
Knowing default parameters for query reduces duplication.
   'post_type' => 'post'
    'orderby' => 'date'
    'order' => 'DESC'
    'posts_per_page' => Value set under Settings -> Reading

Can query for (among many others):
    Author
    Date/time
    Post type
    Taxonomy term assignments
    Meta data
SAMPLE QUERY 1
Five most recent posts
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5
) ); ?>
SAMPLE QUERY 2
Five most recent posts by author with ID 15
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'author' => 15
) ); ?>
SAMPLE QUERY 3
Five most recent posts by author with ID 15 in the toast
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'author' => 15,
        'category_name' => 'toast'
) ); ?>
SAMPLE QUERY 4
Five most recent posts or pages
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'post_type' => array( 'post', 'page' )
) ); ?>
USING THE TAX_QUERY
Introduced in WordPress 3.1
Permits multiple taxonomy queries within a single WP_Query.
Important to remember that the tax_query parameter takes an array of arrays, even if querying
for a single taxonomy term.
Each query accepts up to five arguments:
    taxonomy (required) - string
    field - term_id or slug
    terms (required) - string or array
    include_children - boolean, defaults to true
    operator - string, either AND, IN, or NOT IN
USING THE TAX_QUERY
Using the toast example from Sample Query 3:
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'author' => 15,
        'category_name' => 'toast'
) ); ?>


Becomes
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'author' => 15,
        'tax_query' => array( array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => 'toast'
        ) )
) ); ?>
USING THE TAX_QUERY: MULTIPLE
                  QUERIES
Querying two categories:
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'author' => 15,
        'tax_query' => array( array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => array( 'toast', 'breakfast' ),
                'operator' => 'AND'
        ) )
) ); ?>


Querying a category and a tag:
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'author' => 15,
        'tax_query' => array(
                'relation' => 'AND',
                array(
                        'taxonomy' => 'category',
                        'field' => 'slug',
                        'terms' => 'toast'
                ),
                array(
                        'taxonomy' => 'post_tag',
'field' => 'slug',
                  'terms' => 'wheat'
              )
          )
) ); ?>
USING THE TAX_QUERY: MULTIPLE
                  QUERIES
Querying a category and a tag, excluding subcategories:
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'author' => 15,
        'tax_query' => array(
                'relation' => 'AND',
                array(
                        'taxonomy' => 'category',
                        'field' => 'slug',
                        'terms' => 'toast',
                        'include_children' => false
                ),
                array(
                        'taxonomy' => 'post_tag',
                        'field' => 'slug',
                        'terms' => 'wheat'
                )
        )
) ); ?>
USING THE META_QUERY
Introduced in WordPress 3.1, along with tax_query
Permits multiple post meta queries within a single WP_Query.
Like the tax_query, it is important to note that the meta_query parameter takes an array of
arrays.
Each query accepts up to four arguments:
    key (required) - string
    value - string or array
    compare - string, such as =, !=, or IN. Full list on the WP_Query Codex page.
    type - string, such as NUMERIC or DATE. Full list on the WP_Query Codex page.
USING THE META_QUERY
Five posts with Featured Images
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'meta_query' => array( array(
                'key' => '_thumbnail_id'
        ) )
) ); ?>

Five posts using the same thumbnail, ID 100
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'meta_query' => array( array(
                'key' => '_thumbnail_id',
                'value' => 100,
                'type' => 'NUMERIC'
        ) )
) ); ?>
USING THE META_QUERY: MULTIPLE
              QUERIES
Five posts with Featured Images AND flagged as "featured" posts
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'meta_query' => array(
                array(
                        'key' => '_thumbnail_id'
                ),
                array(
                        'key' => '_featured'
                )
        )
) ); ?>


Five posts with Featured Images OR flagged as "featured" posts
<?php $foo = new WP_Query( array(
        'posts_per_page' => 5,
        'meta_query' => array(
                'relation' => 'OR',
                array(
                        'key' => '_thumbnail_id'
                ),
                array(
                        'key' => '_featured'
                )
        )
) ); ?>
GET_QUERY_VAR();
Used to retrieve a query parameter from the main query.
<?php
         $qty = get_query_var( 'posts_per_page' );
         $post_type = get_query_var( 'post_type' );
?>
IS_MAIN_QUERY();
Introduced in WordPress 3.3
Simple conditional tag that determines whether or not the current query is the main WordPress query.
QUERY_POSTS();
   Evil WordPress function provided to modify or override main query.
   Accepts query arguments as described in the preceeding slides.
   Used within a theme file (archive.php, home.php, index.php, single.php, etc).
   When called, original main query is replaced by the query specified by query_posts().
   Introduces unnecessary performance degredation.

Thankfully, a far-superior alternative exists!
THE PRE_GET_POSTS
         ACTION
Action is executed right before WP_Query parses the query arguments.
Allows any and all query arguments to be modified before a database query is ever run.
Can be used to universally modify queries on a WordPress site, or to modify specific queries.
Rather than placing modifications in individual theme files as is done with query_posts(), changes
can be centralized in functions.php.
USING THE PRE_GET_POSTS ACTION
<?php
           function bwpm_pre_get_posts( $query ) {
                   //Herein, modify the query
           }

           add_action( 'pre_get_posts', 'bwpm_pre_get_posts' );
?>


The $query variable contains an object with two helpful methods:
     get( $query_parameter ) - retrieves a specified query parameter from the current query.
     set( $query_parameter, $value ) - sets a specified query parameter in the current query.
USING THE PRE_GET_POSTS ACTION
Show only five posts on any and every archive page:
<?php
        function bwpm_pre_get_posts( $query ) {
                $query->set( 'posts_per_page', 5 );
        }

        add_action( 'pre_get_posts', 'bwpm_pre_get_posts' );
?>


To do the same on just the front page:
<?php
        function bwpm_pre_get_posts( $query ) {
                if ( $query->is_home() )
                        $query->set( 'posts_per_page', 5 );
        }

        add_action( 'pre_get_posts', 'bwpm_pre_get_posts' );
?>
USING THE PRE_GET_POSTS ACTION
To do the same only when a posts_per_page value isn't set (is using the
WordPress default):
<?php
        function bwpm_pre_get_posts( $query ) {
                if ( ! $query->get( 'posts_page_page' ) )
                        $query->set( 'posts_per_page', 5 );
        }

        add_action( 'pre_get_posts', 'bwpm_pre_get_posts' );
?>
QUESTIONS?

More Related Content

What's hot

Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPVineet Kumar Saini
 
My sql presentation
My sql presentationMy sql presentation
My sql presentationNikhil Jain
 
Getting Creative with WordPress Queries
Getting Creative with WordPress QueriesGetting Creative with WordPress Queries
Getting Creative with WordPress QueriesDrewAPicture
 
Developing applications for performance
Developing applications for performanceDeveloping applications for performance
Developing applications for performanceLeon Fayer
 
MTDDC 2010.2.5 Tokyo - Brand new API
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
 
Powerful Explain in MySQL 5.6
Powerful Explain in MySQL 5.6Powerful Explain in MySQL 5.6
Powerful Explain in MySQL 5.6MYXPLAIN
 
Database performance 101
Database performance 101Database performance 101
Database performance 101Leon Fayer
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimizationBaohua Cai
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
 
PHP performance 101: so you need to use a database
PHP performance 101: so you need to use a databasePHP performance 101: so you need to use a database
PHP performance 101: so you need to use a databaseLeon Fayer
 
Chapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsChapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsVincent Chien
 
56 Query Optimization
56 Query Optimization56 Query Optimization
56 Query OptimizationMYXPLAIN
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain ExplainedJeremy Coates
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Speed Things Up with Transients
Speed Things Up with TransientsSpeed Things Up with Transients
Speed Things Up with TransientsCliff Seal
 

What's hot (20)

Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
My sql presentation
My sql presentationMy sql presentation
My sql presentation
 
Getting Creative with WordPress Queries
Getting Creative with WordPress QueriesGetting Creative with WordPress Queries
Getting Creative with WordPress Queries
 
Developing applications for performance
Developing applications for performanceDeveloping applications for performance
Developing applications for performance
 
MTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APIMTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new API
 
Powerful Explain in MySQL 5.6
Powerful Explain in MySQL 5.6Powerful Explain in MySQL 5.6
Powerful Explain in MySQL 5.6
 
Database performance 101
Database performance 101Database performance 101
Database performance 101
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimization
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
PHP performance 101: so you need to use a database
PHP performance 101: so you need to use a databasePHP performance 101: so you need to use a database
PHP performance 101: so you need to use a database
 
Chapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsChapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfs
 
Recursive Query Throwdown
Recursive Query ThrowdownRecursive Query Throwdown
Recursive Query Throwdown
 
56 Query Optimization
56 Query Optimization56 Query Optimization
56 Query Optimization
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain Explained
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Speed Things Up with Transients
Speed Things Up with TransientsSpeed Things Up with Transients
Speed Things Up with Transients
 
PHP array 1
PHP array 1PHP array 1
PHP array 1
 

Similar to WP_Query, pre_get_posts, and eliminating query_posts()

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
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012l3rady
 
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
 
You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)andrewnacin
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryl3rady
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
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
 
[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
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress sitereferences
 
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
 
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
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
 
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
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingErick Hitter
 
Digging into WordPress custom fields - WordCamp Brno 2017
Digging into WordPress custom fields - WordCamp Brno 2017Digging into WordPress custom fields - WordCamp Brno 2017
Digging into WordPress custom fields - WordCamp Brno 2017Magdalena Paciorek
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)tompunk
 

Similar to WP_Query, pre_get_posts, and eliminating query_posts() (20)

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
 
Victoria wordpress
Victoria wordpressVictoria wordpress
Victoria wordpress
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012
 
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
 
You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)You Don't Know Query (WordCamp Netherlands 2012)
You Don't Know Query (WordCamp Netherlands 2012)
 
Wp query
Wp queryWp query
Wp query
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know query
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
[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
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
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
 
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
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
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
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment Caching
 
Digging into WordPress custom fields - WordCamp Brno 2017
Digging into WordPress custom fields - WordCamp Brno 2017Digging into WordPress custom fields - WordCamp Brno 2017
Digging into WordPress custom fields - WordCamp Brno 2017
 
WP_Query Overview
WP_Query OverviewWP_Query Overview
WP_Query Overview
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

WP_Query, pre_get_posts, and eliminating query_posts()

  • 1. FUN WITH WP_QUERY Erick Hitter @ethitter Lead WordPress Developer at Oomph, Inc. WordPress 3.3 Core Contributor WordCamp Boston Organizer Plugin Author
  • 2. WHAT IS WP_QUERY? WordPress class defined in wp-includes/query.php. Responsible for majority of post-type retrieval from database. Any front-end request made to WordPress is fulfilled by WP_Query in what I refer to as the main query. Used extensively by WordPress but also available to developers.
  • 3. USING WP_QUERY Most often, this is done in "The Loop" to use the results from the main query. <?php if ( have_posts() ) { while( have_posts() ) { the_post(); } } ?>
  • 4. USING WP_QUERY: NEW WP_QUERY(); <?php $queried_posts = new WP_Query(); if ( $queried_posts->have_posts() ) { while( $queried_posts->have_posts() ) { $queried_posts->the_post(); //Use functions such as the_title() and the_content() here. } } wp_reset_query(); wp_reset_postdata(); ?> Creates a new object of the type WP_Query, setting up another instance of The Loop. wp_reset_query() and wp_reset_postdata() are necessary to restore the main WordPress query. More on this later. Best used whenever Template Tags are needed.
  • 5. USING WP_QUERY: GET_POSTS(); <?php $queried_posts = get_posts(); foreach( $queried_posts as $queried_post ) { setup_postdata( $queried_post ); } wp_reset_postdata(); ?> get_posts() generates an array of post objects that match the query parameters. setup_postdata() and wp_reset_postdata() can be used if Template Tags, such as the_title(), are needed. Best used when Template Tags aren't needed or post data will be repurposed, such as generating an array of post IDs.
  • 6. RESETTING QUERY AND POSTDATA After using new WP_Query(), calling wp_reset_query() and wp_reset_postdata() restores the original query and postdata. After using setup_postdata(), calling wp_reset_postdata() restores the post. Calling the two reset functions ensures that the Conditional Tags operate as expected and balance of page renders properly.
  • 7. QUERY BASICS Can pass parameters as an array or query string. <?php $foo = new WP_Query( array( 'posts_per_page' => 5 ) ); $bar = new WP_Query( 'posts_per_page=5' ); ?> Array format is more flexible and necessary for queries such as: 'post__not_in' 'tax_query' 'meta_query' Query string format is parsed into an array by the WP_Query class.
  • 8. QUERY PARAMETERS Extensive list in the Codex at http://codex.wordpress.org/Class_Reference/WP_Query#Parameters Knowing default parameters for query reduces duplication. 'post_type' => 'post' 'orderby' => 'date' 'order' => 'DESC' 'posts_per_page' => Value set under Settings -> Reading Can query for (among many others): Author Date/time Post type Taxonomy term assignments Meta data
  • 9. SAMPLE QUERY 1 Five most recent posts <?php $foo = new WP_Query( array( 'posts_per_page' => 5 ) ); ?>
  • 10. SAMPLE QUERY 2 Five most recent posts by author with ID 15 <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'author' => 15 ) ); ?>
  • 11. SAMPLE QUERY 3 Five most recent posts by author with ID 15 in the toast <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'author' => 15, 'category_name' => 'toast' ) ); ?>
  • 12. SAMPLE QUERY 4 Five most recent posts or pages <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'post_type' => array( 'post', 'page' ) ) ); ?>
  • 13. USING THE TAX_QUERY Introduced in WordPress 3.1 Permits multiple taxonomy queries within a single WP_Query. Important to remember that the tax_query parameter takes an array of arrays, even if querying for a single taxonomy term. Each query accepts up to five arguments: taxonomy (required) - string field - term_id or slug terms (required) - string or array include_children - boolean, defaults to true operator - string, either AND, IN, or NOT IN
  • 14. USING THE TAX_QUERY Using the toast example from Sample Query 3: <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'author' => 15, 'category_name' => 'toast' ) ); ?> Becomes <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'author' => 15, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => 'toast' ) ) ) ); ?>
  • 15. USING THE TAX_QUERY: MULTIPLE QUERIES Querying two categories: <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'author' => 15, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( 'toast', 'breakfast' ), 'operator' => 'AND' ) ) ) ); ?> Querying a category and a tag: <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'author' => 15, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => 'toast' ), array( 'taxonomy' => 'post_tag',
  • 16. 'field' => 'slug', 'terms' => 'wheat' ) ) ) ); ?>
  • 17. USING THE TAX_QUERY: MULTIPLE QUERIES Querying a category and a tag, excluding subcategories: <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'author' => 15, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => 'toast', 'include_children' => false ), array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => 'wheat' ) ) ) ); ?>
  • 18. USING THE META_QUERY Introduced in WordPress 3.1, along with tax_query Permits multiple post meta queries within a single WP_Query. Like the tax_query, it is important to note that the meta_query parameter takes an array of arrays. Each query accepts up to four arguments: key (required) - string value - string or array compare - string, such as =, !=, or IN. Full list on the WP_Query Codex page. type - string, such as NUMERIC or DATE. Full list on the WP_Query Codex page.
  • 19. USING THE META_QUERY Five posts with Featured Images <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'meta_query' => array( array( 'key' => '_thumbnail_id' ) ) ) ); ?> Five posts using the same thumbnail, ID 100 <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'meta_query' => array( array( 'key' => '_thumbnail_id', 'value' => 100, 'type' => 'NUMERIC' ) ) ) ); ?>
  • 20. USING THE META_QUERY: MULTIPLE QUERIES Five posts with Featured Images AND flagged as "featured" posts <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'meta_query' => array( array( 'key' => '_thumbnail_id' ), array( 'key' => '_featured' ) ) ) ); ?> Five posts with Featured Images OR flagged as "featured" posts <?php $foo = new WP_Query( array( 'posts_per_page' => 5, 'meta_query' => array( 'relation' => 'OR', array( 'key' => '_thumbnail_id' ), array( 'key' => '_featured' ) ) ) ); ?>
  • 21. GET_QUERY_VAR(); Used to retrieve a query parameter from the main query. <?php $qty = get_query_var( 'posts_per_page' ); $post_type = get_query_var( 'post_type' ); ?>
  • 22. IS_MAIN_QUERY(); Introduced in WordPress 3.3 Simple conditional tag that determines whether or not the current query is the main WordPress query.
  • 23. QUERY_POSTS(); Evil WordPress function provided to modify or override main query. Accepts query arguments as described in the preceeding slides. Used within a theme file (archive.php, home.php, index.php, single.php, etc). When called, original main query is replaced by the query specified by query_posts(). Introduces unnecessary performance degredation. Thankfully, a far-superior alternative exists!
  • 24. THE PRE_GET_POSTS ACTION Action is executed right before WP_Query parses the query arguments. Allows any and all query arguments to be modified before a database query is ever run. Can be used to universally modify queries on a WordPress site, or to modify specific queries. Rather than placing modifications in individual theme files as is done with query_posts(), changes can be centralized in functions.php.
  • 25. USING THE PRE_GET_POSTS ACTION <?php function bwpm_pre_get_posts( $query ) { //Herein, modify the query } add_action( 'pre_get_posts', 'bwpm_pre_get_posts' ); ?> The $query variable contains an object with two helpful methods: get( $query_parameter ) - retrieves a specified query parameter from the current query. set( $query_parameter, $value ) - sets a specified query parameter in the current query.
  • 26. USING THE PRE_GET_POSTS ACTION Show only five posts on any and every archive page: <?php function bwpm_pre_get_posts( $query ) { $query->set( 'posts_per_page', 5 ); } add_action( 'pre_get_posts', 'bwpm_pre_get_posts' ); ?> To do the same on just the front page: <?php function bwpm_pre_get_posts( $query ) { if ( $query->is_home() ) $query->set( 'posts_per_page', 5 ); } add_action( 'pre_get_posts', 'bwpm_pre_get_posts' ); ?>
  • 27. USING THE PRE_GET_POSTS ACTION To do the same only when a posts_per_page value isn't set (is using the WordPress default): <?php function bwpm_pre_get_posts( $query ) { if ( ! $query->get( 'posts_page_page' ) ) $query->set( 'posts_per_page', 5 ); } add_action( 'pre_get_posts', 'bwpm_pre_get_posts' ); ?>