1. Code
  2. Coding Fundamentals
  3. Rest API

Mastering WP_Query: 10 Useful Examples

Scroll to top
This post is part of a series called Mastering WP_Query.
WP_Query Arguments: Author, Search, Password & Permissions
Combining WP_Query With the Main Query

Now that we've learned almost everything about the WP_Query class, it's time to try out some examples. In this part, we're going to work on ten different scenarios to utilize the WP_Query class and related functions.

It will be a fun exercise and I hope it will be equally educational. Let's begin!

A Quick Tutorial on Creating a Loop With WP_Query

Just as a refresher, here is a mini-tutorial on creating WordPress loops with the WP_Query class. It's no different from creating a regular loop, really. A typical WordPress loop goes like this:

1
<?php
2
3
if ( have_posts() ) {
4
    while ( have_posts() ) {
5
        the_post();
6
        // Post data goes here.

7
    }
8
}
9
10
?>

And creating a loop with the WP_Query class has only a few differences:

1
<?php
2
3
$args = array(
4
    'category_name' => 'news',
5
    'posts_per_page' => 3
6
);
7
8
$my_query = new WP_Query( $args );
9
10
if ( $my_query->have_posts() ) {
11
    while ( $my_query->have_posts() ) {
12
        $my_query->the_post();
13
        // Post data goes here.

14
    }
15
}
16
17
// Reset the `$post` data to the current post in main query.

18
wp_reset_postdata();
19
20
?>

Let's see the differences in the second version:

  • We set some arguments for our WP_Query instance.
  • We instantiated the WP_Query class.
  • We added $my_query-> to the beginning of the have_posts() and the_post() functions (so they're now the methods of the WP_Query class).
  • We reset the data of $post so it can return to the main query.

Now we know how to create a loop with WP_Query and the difference between a regular loop and a loop created with WP_Query. We're not going to create loops in every example (for the sake of keeping the tutorial short and on topic), so you can refer to this section if you need to create a loop with the examples below.

Example #1: All an Author's Posts This Year

Let's say that you want to list a specific author's posts written in the current year in a special Author's Posts This Year section. A simple combination of two WP_Query parameters will suffice:

1
<?php
2
3
// Get the year we're in.

4
$current_year = date( 'Y' );
5
6
// Setup arguments.

7
$args = array(
8
    // Get the author with the nicename "john".

9
    'author' => 'john',
10
    // Get his posts from this year.

11
    'year'   => $current_year
12
);
13
14
// Instantiate new query instance.

15
$my_query = new WP_Query( $args );
16
17
?>

Pass this query in a loop, and you're good to go!

Example #2: Latest Posts From This Category (Except the Current Post)

Let's say that you want to create a loop under each post in their single post pages, and list the latest posts from the category that the post is in. Of course, you have to exclude the current post in case it might be one of the latest posts from that category. Here's how you create the query with the 'cat' and 'post__not_in' parameters:

1
<?php
2
3
// Get the current post id.

4
$current_post_id = get_the_ID();
5
6
// Get the current post's category (first one if there's more than one).

7
$current_post_cats = get_the_category();
8
$current_post_first_cat_id = $current_post_cats[ 0 ]->term_id;
9
10
// Setup arguments.

11
$args = array(
12
    // Get category's posts.

13
    'cat' => $current_post_first_cat_id,
14
    // Exclude current post.

15
    'post__not_in' => array( $current_post_id )
16
);
17
18
// Instantiate new query instance.

19
$my_query = new WP_Query( $args );
20
21
?>

For the loop, I suggest creating three or four columns with post thumbnails above post titles. It will look really nice right under the post and before the comments section.

Example #3: Most Popular Posts Ordered by Comment Count

WordPress doesn't have a built-in post view count system, and plugins that provide this functionality are famous for slowing down the website (because on each post view, the plugins write in the database over and over again to record the view counts). However, there's another kind of measurement to determine which posts are most popular: counting comments. And unlike view counts, comment counts are already in the database—the WP_Query class makes it super easy to order posts by comment count:

1
<?php
2
3
// Setup arguments.

4
$args = array(
5
    // Order by comment count.

6
    'orderby' => 'comment_count'
7
);
8
9
// Instantiate new query instance.

10
$my_query = new WP_Query( $args );
11
12
?>

See how easy this is? Now imagine creating a custom page template with a loop running this query—a Most Commented Posts page.

Example #4: A Simple Slider Setup

When using WordPress to build corporate websites, portfolios, or web magazines, sliders have become a must-have industrial standard. I'm not really a fan of sliders (I think it's bad UX), but the web seems to like it, so I can't just say no to my clients while making websites for them. If they want sliders, I use a simple query using the WP_Query class:

1
<?php
2
3
// Setup arguments.

4
$args = array(
5
    // Get the "slider" post type.

6
    'post_type' => 'slider',
7
    // Get a specific slider category.

8
    'category_name' => 'home-slides',
9
    // Get all slides and don't paginate.

10
    'nopaging' => true
11
);
12
13
// Instantiate new query instance.

14
$my_query = new WP_Query( $args );
15
16
?>

The 'cat' argument can be used to retrieve slides from different categories so you can separate slide groups and use multiple sliders on multiple pages. If you're going to use just one slider on your website, you can delete that line and you're good to go.

Example #5: A Random Quote in the Sidebar

If you're keen on literature or religion, you might want to have some of your favorite quotes in the sidebar—it's not a waste of space if you use the area with purpose. So, if you're going to list a random quote in your sidebar on each page view, you can use the following code snippet to create the post type and use the following query to create a loop in your sidebar:

1
<?php
2
3
/* 

4
 * Create new post type called "Quotes"

5
 * (refer to the `register_post_type` function to

6
 * learn more about creating custom post types).

7
 */
8
function quote_post_type() {
9
    
10
    $args = array(
11
        'label' => 'Quotes',
12
        'public' => true
13
    );
14
    
15
    register_post_type( 'quotes', $args );
16
}
17
18
add_action( 'init', 'quote_post_type' );
19
20
// Setup arguments.

21
$args = array(
22
    // Get the "quotes" psot type.

23
    'post_type' => 'quotes',
24
    // Randomize the order.

25
    'orderby' => 'rand',
26
    // Get only one item.

27
    'posts_per_page' => 1,
28
);
29
30
// Instantiate new query instance.

31
$my_query = new WP_Query( $args );
32
33
?>

An easy and elegant solution.

Example #6: Listing Products Between a Price Range

I found this example on Scribu.net, and I must say, it might be the best WP_Query trick in this tutorial. It's a bit more technical than the others, too, because it can be applied to a WordPress-powered eCommerce website in this context.

Here's the code snippet you'll use if you want to list items from a custom Product post type and filter the results with the price custom fields:

1
<?php
2
3
// Source: https://scribu.net/wordpress/advanced-metadata-queries.html

4
5
// Setup arguments.

6
$args = array(
7
    // Get the "product" post type.

8
    'post_type' => 'product',
9
    // Setup the "meta query".

10
    'meta_query' => array(
11
        array(
12
            // Get the "price" custom field.

13
            'key' => 'price',
14
            // Set the price values.

15
            'value' => array( 100, 200 ),
16
            // Set the compare operator.

17
            'compare' => 'BETWEEN',
18
            // Only look at numeric fields.

19
            'type' => 'numeric',
20
        )
21
    )
22
);
23
24
// Instantiate new query instance.

25
$my_query = new WP_Query( $args );
26
27
?>

A big kudos to Silviu-Cristian Burca!

Example #7: A Shortcode to Embed Posts Inside Posts

Here's a fun exercise—and we get to use the Shortcode API too! In this example, we're going to create a shortcode that can embed a post within a post. (I hardly contained myself from naming the shortcode [postception].) In the following code snippet, we create a shortcode function that allows us to embed posts (or any custom post type) and lets us choose whether to show the full post or just an excerpt:

1
<?php
2
3
/*

4
 * Usage:

5
 *

6
 * [embed_post slug="my-post"]

7
 * [embed_post slug="my-post" full="false"]

8
 * [embed_post type="movie" slug="inception"]

9
 */
10
11
function tutsplus_embedded_post_shortcode( $attributes ) {
12
13
    // Extract shortcode attributes.

14
    extract(
15
        shortcode_atts(
16
            array(
17
                'type' => 'post',
18
                'slug' => '',
19
                'full' => true
20
            ),
21
            $attributes
22
        )
23
    );
24
25
    // Setup arguments.

26
    $args = array(
27
        // Get post type ("post" by default).

28
        'post_type' => $type,
29
        // Get post by slug.

30
        'name' => $slug
31
    );
32
33
    // Instantiate new query instance.

34
    $my_query = new WP_Query( $args );
35
36
    // Check that we have query results.

37
    if ( $my_query->have_posts() ) {
38
39
        // Begin generating markup.

40
        $output = '<section class="embedded-post">';
41
42
        // Start looping over the query results.

43
        while ( $my_query->have_posts() ) {
44
45
            $my_query->the_post();
46
47
            // Add title to output.

48
            $output .= '<h2 class="embedded-post-title">';
49
                $output .= get_the_title();
50
            $output .= '</h2>';
51
52
            // Get full post if `$full` is true, otherwise, show the get excerpt

53
            if ( 'true' === $full ) {
54
55
                // Add full content to output.

56
                $output .= '<div class="embedded-post-content">';
57
                    $output .= get_the_content();
58
                $output .= '</div>';
59
60
            } else {
61
62
                // Add excerpt to output.

63
                $output .= '<div class="embedded-post-excerpt">';
64
                    $output .= get_the_excerpt();
65
                    $output .= '&hellip; <a href="' . get_permalink() . '">' . __( 'See full post', 'tutsplus' ) . ' &raquo;</a>';
66
                $output .= '</div>';
67
68
            }
69
70
        }
71
72
        // End generating markup.

73
        $output .= '</section>';
74
75
    } else {
76
77
        // Output message to let user know that no posts were found.

78
        $output = '<section class="embedded-post-error">';
79
            $output .= '<p>' . __( 'No posts found.', 'tutsplus' ) . '</p>';
80
        $output .= '</section>';
81
82
    }
83
84
    wp_reset_postdata();
85
86
    return $output;
87
88
}
89
90
add_shortcode( 'embed_post', 'tutsplus_embedded_post_shortcode' );
91
92
?>

Example #8: List of Current Scheduled Posts (With Optional Excerpts)

Here's an idea: Why don't you display some sneak peeks of your upcoming posts to your visitors? You can use the following function to list your scheduled posts with or without excerpts after the titles:

1
<?php
2
3
/*

4
 * Usage with Excerpts:

5
 * <?php echo tutsplus_show_drafts(); ?>

6
 *

7
 * Usage without Excerpts:

8
 * <?php echo tutsplus_show_drafts( false ); ?>

9
 */
10
11
function tutsplus_show_drafts( $show_excerpts = true ) {
12
13
    // Setup arguments.

14
    $args = array(
15
        'post_status' => 'future',
16
        'nopaging' => true
17
    );
18
19
    // Instantiate new query instance.

20
    $my_query = new WP_Query( $args );
21
22
    // Check that we have query results.

23
    if ( $my_query->have_posts() ) {
24
25
        // Begin generating markup.

26
        $output = '<section class="pending-posts">';
27
28
        // Start looping over the query results.

29
        while ( $my_query->have_posts() ) {
30
31
            $my_query->the_post();
32
33
            // Output draft post title and excerpt (if enabled).

34
            $output .= '<div class="pending">';
35
                $output .= '<h3 class="pending-title">' . get_the_title() . '</h3>';
36
                    $output .= get_the_title();
37
                $output .= '</h3>';
38
39
                if ( $show_excerpts ) {
40
41
                    $output .= '<div class="pending-excerpt">';
42
                        $output .= get_the_excerpt();
43
                    $output .= '</div>';
44
45
                }
46
47
            $output .= '</div>';
48
49
        }
50
51
        // End generating markup.

52
        $output .= '</section>';
53
54
    } else {
55
56
        // Let user know that nothing was found.

57
        $output = '<section class="drafts-error">';
58
            $output .= '<p>' . __( 'Nothing found', 'tutsplus' ) . '</p>';
59
        $output .= '</section>';
60
61
    }
62
63
    wp_reset_postdata();
64
65
    return $output;
66
67
}
68
69
?>

Example #9: Post From a Year Ago Today

If your blog is older than a year, and your content is timeless (meaning either a person from 2022 or 2032 could find the article relevant), adding a Post From a Year Ago Today section might boost your page views. Here's how you do it:

1
<?php
2
3
// Setup arguments.

4
$args = array(
5
    // Day (1 - 31).

6
    'day' => date( 'j' ),
7
    // Month (1 - 12).

8
    'monthnum' => date( 'n' ),
9
    // Year (minus 1).

10
    'year' => date( 'Y' ) - 1,
11
    // Show only one post.

12
    'posts_per_page' => 1
13
);
14
15
// Instantiate new query instance.

16
$my_query = new WP_Query( $args );
17
18
?>

Use this query to build a loop that displays a single post from yesteryear.

Example #10: Show Children of the Current Page

What if you have nothing other than the titles of sub-pages to put on your Services, Our Works, or My Portfolio page? Maybe an intro paragraph, but you're right, those pages are doomed to be placeholders. Still, it's a good idea to place sub-pages in there—maybe a grid with square thumbnails and titles below. Let's see which query we should use when creating such a page template:

1
<?php
2
3
$current_page_id = get_the_ID();
4
5
// Setup arguments.

6
$args = array(
7
    // Get children of current page.

8
    'parent' => $current_page_id,
9
    // Disable pagination.

10
    'nopaging' => true
11
);
12
13
// Instantiate new query instance.

14
$my_query = new WP_Query( $args );
15
16
?>

Key Points to Remember About WP_Query

The WP_Query class gives you a lot of power when looping through post data on your WordPress website. It comes with plenty of options to help you narrow down the list of posts that you want to output. However, there are a few things that you should keep in mind.

Main Query vs. Secondary Queries

There are two types of queries in WordPress. The first one is run automatically by WordPress when you visit a webpage by analyzing the URL that you want to visit. This is the main query. Keep in mind that the main query might not always be the first query to be executed by WordPress.

All other types of queries besides the one created by WordPress based on the requested URL are secondary queries. Examples of secondary queries are the queries that we created in the previous sections.

Resetting Data After Running the Query

You should always call the wp_reset_postdata() function after running your custom or secondary query. This function will restore the value of the global $post variable so that it contains information about the main post. In other words, it basically restores the context of template tags from the secondary query loop to the main query loop.

There is another function similar to wp_reset_postdata() called wp_reset_query(). The difference between these two is that the latter function resets the main query to the original main query and then calls wp_reset_postdata().

You will only ever need to call wp_reset_query() if you have used the query_posts() function somewhere in your code. However, you should avoid calling the query_posts() function either within themes or inside plugins as this function will change your main query.

Altering the Main Query

What if you want to make changes to the main query? You should do that by using the pre_get_posts action and then using the is_main_query() method to make sure you are working with the main query. Here is an example:

1
<?php
2
3
function search_blacklist($query) {
4
    if ( ! is_admin() && $query->is_main_query() && $query->is_search()) {
5
        $query->set( 'post__not_in', array( 218 ) );
6
    }
7
}
8
add_action( 'pre_get_posts', 'search_blacklist' );
9
10
?>

Here we are using the pre_get_posts hook to execute a function which will prevent posts with specific ids from appearing in search results. You can write variations of the above functions to limit search results to a specific date, category, etc.

Wrapping Up

I hope you enjoyed these examples as much as I did while preparing them. I paid special attention to giving varying examples both to be fun and to spark your creativity. If you liked the article, don't forget to share it with your friends!

In the next part, we'll talk about WP_User_Query, one of the sister classes of WP_Query. See you then!

This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time working on personal projects that make his everyday life easier or taking long evening walks with friends.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.