Learn How to Use WP_Query

Introduction

The below is primarily sourced from Rachel McCollin and Baris Unvers’ series Mastering WP_Query.

Fundamental Concepts

  • On each page WP runs a query, the specifics of which is determined by the type of page – e.g. a query to display a single post as opposed to a query to display a list of posts.
  • Using WP_Query (a class, code: includes/query.php) one can display content besides that created by the default WP query on each page.
  • WP_Query consists of four components:
    • Arguments of query
    • Query
    • Loop (displays data)
    • Clean Up – Use wp_reset_post_data() so that query is the main (default) query.
  • Alternatives to WP_Query:
    • pre_get_posts – hook to modify main query. Use when you want to modify the main (default) query.
    • get_posts() / get_pages() – use WP_Query, are template tags, perform simpler queries limited to posts/pages.
    • query_posts() – McCollin suggests this should not be utilized at all.
  • See this article by McCollin on examples of when WP_Query can be useful.
  • The query is displayed by the loop.
    • Thus the loop occurs after the query.
    • Components of The Loop
      • if( $query->have_posts() ) – Check if there are any results from the query.
      • while( $query->have_posts() ) – Repeat loop for each result.
      • $query->the_post() – Access the specific result.

Basic Format of Query

[php]
<?php

$args = array(
// Arguments for query.
);

// Custom Query.
$query = new WP_Query( $args );

// Check for Query Results.
if ( $query->have_posts() ) {

// Loop through each query result.
while ( $query->have_posts() ) {
$query->the_post();
// Code to interact with query result.
}

// Restore original post data.
wp_reset_postdata();

?>
[/php]