Skip to content

Here’s How to Retrieve Any Post You Want With WP_Query

If you’ve built simple themes in the past, chances are the need to retrieve posts on your own didn’t arise. After all, WordPress loads the most recent ten posts on the main page and the correct posts on archive pages. What about more complex scenarios? What if you would like a sitemap of sorts and you want to list all your posts and pages ordered by date?

WP_Query is your friend, it allows you to pull posts from the database according to your criteria. You can retrieve all posts from a single category that contain certain tags as well. You could retrieve all pages created last year and posts which do not have a featured image.

In this post I’ll give you an in-depth look into how WP_Query works – let’s get started!

Retrieve Any Post You Want With WP_Query

📚 Table of contents:

A Custom Loop

The key to working well with custom queries is mastering the arguments you can pass to them. Before we look at this, let’s create a quick “skeleton” we can use to list posts. The loop on a regular archive page would look something like this:

<?php if ( have_posts() ) : ?>
	<?php while( have_posts() ) : the_post() ?>
		<!-- Display Post Here -->
	<?php endwhile ?>
<?php else : ?>
	<!-- Content If No Posts -->
<?php endif ?>Code language: HTML, XML (xml)

This works just fine because before the page is loaded, WordPress has already retrieved the correct posts. When we write a custom query we’ll need a custom loop. The code is very similar, here goes:

<?php 
$args = array( 
	'post_type'   => 'post',
	'post_status' => 'future'
);
$scheduled = new WP_Query( $args );

if ( $scheduled->have_posts() ) : 
?>
	<?php while( $scheduled->have_posts() ) : $scheduled->the_post() ?>
		<!-- Display Post Here -->
	<?php endwhile ?>
<?php else : ?>
	<!-- Content If No Posts -->
<?php endif ?>Code language: HTML, XML (xml)

We create a new WordPress query using the WP_Query class, passing it parameters to specify the types of posts we need. We then call the have_posts() and the_post() methods on our $scheduled object.

If you’re new to object oriented programming and don’t really understand why, don’t worry, you can still easily use custom queries. We’ll be focusing on the $args array throughout the post which will be pretty straightforward.

Simple Arguments

As I mentioned, the main “body of knowledge” when it comes to WP_Query lies in its arguments. The Codex lists all of them, we’ll take a look at the most useful ones here.

Some arguments are pretty simple, such as the tag or tag_id parameter. The former takes a tag slug, the later a tag id. You can also separate multiple items with commas or use negative ids to indicate that you want to retrieve posts that do not have that particular tag attached.

$args = array( 
	'post_type'   => 'post',
	'tag_id'      => '22,92,44,-21'
);
$our_posts = new WP_Query( $args );Code language: PHP (php)

The snippet would retrieve articles which have any of the first three tags attached to them, but not the fourth. While this system is powerful enough for simple needs, I usually use the far more flexible taxonomy query which I’ll discuss a bit later.

The author, author_name, cat, category_name, s (for search terms), post_status, post_type are examples of some more simple fields. Note that some fields, like post_status require you to pass an array of statuses if you want to use multiple values.

$args = array( 
	'post_type'   => array( 'post', 'page' ),
	'post_status' => array( 'draft', 'publish' ),
	'cat'         => 'music,videos'
);
$our_posts = new WP_Query( $args );Code language: PHP (php)

The example above retrieves any posts that are either pages, posts; are either published or in draft status and have either the music or videos category assigned. This could be used for displaying the titles of any current or planned content related to music or videos.

Taxonomy Queries

For simple stuff, using the mentioned arguments to retrieve posts based on categories or tags is enough but what if you have a custom taxonomy, or you need to combine multiple parameters? The answer lies in the tax_query argument which is itself an array. Let’s look at an example first.

$args = array(
	'post_type' => 'book',
	'tax_query' => array(
		array(
			'taxonomy' => 'genre',
			'field'    => 'slug',
			'terms'    => array( 'scifi', 'thriller' ),
			'operator' => 'NOT IN',
		),
		array(
			'taxonomy' => 'author',
			'field'    => 'id',
			'terms'    => array( 92, 883, 399 ),
		),
		'relation' => 'AND',
	),
);
$query = new WP_Query( $args );Code language: PHP (php)

Here we retrieve some posts from our ‘book’ post type, adding some taxonomy parameters. Using two arrays defined within the tax_query we’ve specified that we want to pull books written by author’s 92, 883 or 399 which are not in the sci-fi or thriller genre. The relation parameter defines the relationship between the two arrays. In our case it is an ‘and’ relationships which means that both conditions must be met.

If we used ‘or’ we would have retrieved books which are either not in the sci-fi or thriller category or they are written by the specified three authors. In plain English this means: I want to see all my books except for the sci-fi and thriller genre. However, I want to see all books from Terry Pratchett, Douglas Adams and Stephen King, regardless of genre.

Meta Queries

Meta queries are very similar to taxonomy queries in structure but they use data from the post meta table to filter posts. The code below will display all published posts which have a featured image.

$args = array(
	'post_type' => 'post',
	'meta_query' => array(
		array(
			'key'     => '_thumbnail_id',
			'value'   => '',
			'compare' => '!=',
		),
	),
);
$query = new WP_Query( $args );Code language: PHP (php)

WordPress stores the ID of the featured image for a post using the _thumbnail_id field. So if we retrieve all posts where this meta value is not empty, we should end up with all posts which have a featured image.

The secret here is knowing how to use the compare property and type. You can use a multitude of values which should be familiar from SQL: ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘EXISTS’ (from WordPress 3.5 and up), and ‘NOT EXISTS’ (from WordPress 3.5 and up)

The type property is usually important when you want to compare numbers or dates. Possible values are ‘NUMERIC’, ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’, ‘UNSIGNED’. Keep in mind to use NUMERIC when comparing numbers, in most other cases you should be fine.

Just like with taxonomy queries you can stack multiple requirements and then use relation parameter to specify the relationship between them.

$args = array(
	'post_type' => 'post',
	'meta_query' => array(
		'relation' => 'OR',
		array(
			'key'     => 'mood',
			'value'   => array( 'happy', 'awesome' ),
			'compare' => 'IN',
		),
		array(
			'key'     => 'income',
			'value'   => 500,
			'compare' => '>',
			'type'    => 'NUMERIC'
		),
	),
);
$query = new WP_Query( $args );Code language: PHP (php)

The example above would display posts from a hypothetical diary where something good happened. I either felt happy or awesome or I made more than $500 that day.

Date Parameters

Dates can get a bit complex, but are very flexible. The WP_Query Documentation has plenty of examples if you need more information.

Retrieving posts from a certain time is pretty easy. You can use the year, monthnum, w (week of the year), day and a couple of other parameters to specify a time. The code below would retrieve all posts from the March of 2013.

$args = array(
	'post_type' => 'post',
	'year' => 2013,
	'month' => 3
);
$query = new WP_Query( $args );Code language: PHP (php)

If you want to get into more complex time ranges you’ll need to use date_query. This allows you to specify arbitrary ranges quite easily, using a familiar array format. The following example – courtesy of the Codex – shows how you can retrieve posts which were written between 9AM and 5PM on weekdays.

$args = array(
	'post_type' => 'post',
	'date_query' => array(
		array(
			'hour'      => 9,
			'compare'   => '>=',
		),
		array(
			'hour'      => 17,
			'compare'   => '<=',
		),
		array(
			'dayofweek' => array( 2, 6 ),
			'compare'   => 'BETWEEN',
		),
	),
);
$query = new WP_Query( $args );Code language: PHP (php)

Ordering Results

The order in which a list is presented is just as important as the elements within. Thankfully WordPress offers us the order_by and order parameters. The order parameter is pretty straightforward, you can use ASC or DESC to order ascending or descending.

The order_by parameter can take on a number of values: ‘none’, ‘ID’, ‘author’, ‘title’, ‘name’, ‘type’, ‘date’, ‘modified’, ‘parent’, ‘rand’, ‘comment_count’, ‘menu_order’, ‘meta_value’, ‘meta_value_num’, ‘post__in’. Ordering by meta_value can be especially useful. In this case, don’t forget to specify the meta_key field as well.

$args = array(
	'post_type' => 'painting',
	'meta_query' => array(
		array(
			'key'     => 'price',
			'value'   => 50000,
			'compare' => '>',
			'type'    => 'NUMERIC'
		),
	),
	'order_by' => 'meta_value_num',
	'meta_key' => 'price'
);
$query = new WP_Query( $args );Code language: PHP (php)

This example retrieves paintings which are valued over $50,000 and orders them ascending by price. Note that since the price is stored as a number I used meta_value_num to order the results, as opposed to meta_value which would be used for strings.

Another ordering worth a mention is post__in. This post__in is a parameter in its own right, it allows you to specify an array of post ids to retrieve. By default, WordPress orders posts by date, the order you specified in the post__in is not preserved. If you use post__in as the order by value as well, WordPress will preserve the order.

$args = array(
	'post_type' => 'post',
	'post__in' => array( 23, 441, 12, 322, 34, 33),
	'order_by' => 'post__in',
);
$query = new WP_Query( $args );Code language: PHP (php)

Wrapping Up

I hope it’s clear from this introduction to WP_Query that this is indeed a powerful class. It allows you to retrieve posts using your own criteria in a WP-standard way. Take a look at its documentation for more information and some great properties and methods this class offers to manipulate the query and the loop.

WP_Query is a part of what makes WordPress a great general CMS – the ability to retrieve objects from the database in a modular and customizable fashion.

📗 Further reading:

If you have any questions do let us know in the comments!

Don’t forget to join our crash course on speeding up your WordPress site. Learn more below:

 

Layout and presentation by Chris Fitzgerald and Karol K.

Yay! 🎉 You made it to the end of the article!
Daniel Pataki
Share:

0 Comments
Inline Feedbacks
View all comments

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!

0
Would love your thoughts, please comment.x