Perform Queries in WordPress with WP_Query

The database that feeds your WordPress website is full of valuable information. This is what makes it possible to filter your posts and pages by many different variables. If what you want to display is not part of your theme, however, there are other ways of using that data. 

This is where WP_Query comes in. This is a PHP class that makes use of a wide variety of parameters. Consequently, it enables you to pull data from the WordPress database for use or display on your website. 

In this article, we’ll provide a deeper understanding of the WP_Query class and how it can be used. We’ll also walk you through some important steps to follow when using it. If you’re ready, let’s dive right in! 

What is WP_Query?

As we mentioned, WP_Query is a PHP class used by the WordPress database. This particular class can do several things, but primarily it’s used to pull posts from the database. 

As its name indicates, it makes a query based on the criteria you set for it. Since there are a lot of parameters you can use with WP_Query in WordPress, you can pull and display posts in a number of unique ways. We’ll explore those options in greater detail later in this post.

How to Use WP_Query

Even if you’re just learning the various aspects of the WordPress codebase, WP_Query is a good class to get started with. Now, let’s break down four different ways you can use it on your website. 

1. Get Started with a Custom Loop 

One of the best ways to get to know the WP_Query call is through the WordPress Loop. If you’re not familiar with what the Loop is, it’s an important concept to read up on.

The Loop is what calls to the database asking for post content, and displays the data that is returned. It also functions based on set parameters, such as how many posts you want your site to display on a single page (something you can configure in your Settings > Reading menu).

The very basics of the Loop look like this:

<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        // Display post content
    endwhile;
endif;
?>

This simple statement is essentially saying that if there are posts, they should be displayed. Of course, you can add a wide variety of template tags to this foundation, in order to create the display you want.

You can also insert WP_Query into the Loop. This enables you to place parameters on what posts will be returned. Let’s break down what that would look like: 

<?php

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

You’ll see the same if/while statements from the basic Loop, but there is an additional WP_Query string. Whatever parameters are set here will determine what posts will be displayed. 

For example, if you wanted to exclude a certain author from a list of posts, you could do that in the Loop with WP_Query: 

$query = new WP_Query( array( 'author' => -12 ) );

By placing this in the Loop, your displayed posts would no longer include the user with the author number of “12”.

The number of parameters you can use with this method are just about endless. You can include category information as well as advanced taxonomies, just to give two examples. 

2. Arguments: The Backbone of Custom Queries in WordPress

In the previous example, you may have noticed “($args)” as a part of the string. This is a vital part of the query that refers to the included ‘arguments’. It tells the database exactly what to include in the returned data. 

Essentially, these arguments can be set up to determine the exact results you want to display. Arguments can be used to change the value of variables as well. For example, if you want to change how your list of categories appears on the page, you can use an argument. 

Your argument will define an array of variables and values. So if you want to, you can use an argument to define an array and tell your database to present the categories in descending order. Additionally, you can use the same method to exclude any categories that don’t contain posts. 

3. Parameters in WP_Query: Category, Tag, and More 

Up to this point, we’ve only mentioned parameters in passing. At this point, let’s look closer at what they can actually do. Their primary function is to enable you to pull custom-designed collections of posts. 

One example of a parameter that can be used in the header of your site is the Category parameter. You can use this to specify specific categories for display. This is done by providing the relevant category number or slug. 

Additionally, you can do the same thing with the Tag parameter. Of course, the Category and Tag parameters are really just the tip of the iceberg when it comes to using WP_Query. 

4. Modify Objects with Methods and Properties 

While it’s not recommended to directly alter the properties of a class like WP_Query, you can interact with them by using methods. Essentially, methods are like functions, while properties are the equivalent of variables

WP_Query has many properties. These range from simple “$posts” properties to more complicated ones. Whatever method is used to interact with them, data will be returned based on the parameters you choose to put in place. 

WP_Query vs. query_posts() in WordPress

It’s worth noting there is another way to modify the main query on your page. This is the query_posts() function. While this can work in a similar way to WP_Query, it can also be very problematic. 

The WordPress Code Reference even strongly advises that you do not use this function inside your website’s main Loop. It’s also best to avoid it in plugins and themes. This is because it will completely override your main query. 

The WP_Query class is preferred, because you can also ‘reset’ the main Loop after you run a query. Since WP_Query allows you to run multiple queries in a loop, you’ll want to understand how to implement the wp_reset_postdata function as well.

If you’ve embedded a secondary loop inside the main WordPress Loop, the reset function will be placed at the end and look like this: 

<?php wp_reset_postdata(); ?>

This will restore the default template tags, and you’ll be back to how things were before your secondary loop was initiated. 

Customize Your WordPress Site with WP Engine 

Being able to make adjustments to how items are displayed on your website is just one of the benefits of using WordPress. Understanding WP_Query and leveraging the tools provided on the developer resources page can help you build truly customized websites. 

Here at WP Engine, we’re passionate about making sure you have the resources you need to build engaging websites. Check out our WordPress solutions and hosting plans today! 

Get started.

Build faster, protect your brand, and grow your business with a WordPress platform built to power remarkable online experiences.

Chat with us!