Now that we 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 10 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 Reminder on Creating a Loop With WP_Query

Just to make this article be understandable separately from the “Mastering WP_Query” series, I should do a nano-tutorial on creating WordPress loops with the WP_Query class.

It’s not different than creating a regular loop, really. A typical WordPress loop goes like this:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

<?php$args=array('category_name'=>'news','posts_per_page'=>3);$my_query=new WP_Query($args);if($my_query->have_posts()){while($my_query->have_posts()){$my_query->the_post();// Post data goes here.}}// Reset the `$post` data to the current post in main query.
wp_reset_postdata();?>

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),

And we reset the data of $post so it can return to the main query.

Now we know how to create a loop with WP_Queryand 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: An Author’s Posts in 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<?php// Get the year we're in.$current_year=date('Y');// Setup arguments.$args=array(// Get the author with the nicename "john".'author'=>'john',// Get his posts from this year.'year'=>$current_year);// Instantiate new query instance.$my_query=new WP_Query($args);?>

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 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

<?php// Get the current post id.$current_post_id= get_the_ID();// Get the current post's category (first one if there's more than one).$current_post_cats= get_the_category();$current_post_first_cat_id=$current_post_cats[0]->term_id;// Setup arguments.$args=array(// Get category's posts.'cat'=>$current_post_first_cat_id,// Exclude current post.'post__not_in'=>array($current_post_id));// Instantiate new query instance.$my_query=new WP_Query($args);?>

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:

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

<?php// Setup arguments.$args=array(// Get the "slider" post type.'post_type'=>'slider',// Get a specific slider category.'category_name'=>'home-slides',// Get all slides and don't paginate.'nopaging'=>true);// Instantiate new query instance.$my_query=new WP_Query($args);?>

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 in 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 religious, 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:

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 e-commerce 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:

<?php// Source: http://scribu.net/wordpress/advanced-metadata-queries.html// Setup arguments.$args=array(// Get the "product" post type.'post_type'=>'product',// Setup the "meta query".'meta_query'=>array(array(// Get the "price" custom field.'key'=>'price',// Set the price values.'value'=>array(100,200),// Set the compare operator.'compare'=>'BETWEEN',// Only look at numeric fields.'type'=>'numeric',)));// Instantiate new query instance.$my_query=new WP_Query($args);?>

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:

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:

Example #9: “Post From a Year Ago Today”

If your blog is older than a year, and your content is timeless (meaning both a person from 2015 and 2025 will find the article relevant), adding a “Post From a Year Ago Today” section might boost your page views. Here’s how you do it:

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

Example #10: Show Children of Current Page

You have nothing other than sub-pages’ titles to put inside 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

<?php$current_page_id= get_the_ID();// Setup arguments.$args=array(// Get children of current page.'parent'=>$current_page_id,// Disable pagination.'nopaging'=>true);// Instantiate new query instance.$my_query=new WP_Query($args);?>