In this part of the series on Mastering WP_Query
, you'll learn about some of the arguments you can use with the WP_Query
class, namely those for:
- status
- order
- pagination
You can use these arguments to fetch scheduled posts from the database, to query attachments, to amend the way posts are ordered and what they're ordered by, to specify how many posts are displayed, and much more
But before you can do this, you need to understand how arguments work in WP_Query
.
A Recap on How Arguments Work in WP_Query
Before we start, let's have a quick recap on how arguments work in WP_Query
. When you code WP_Query
in your themes or plugins, you need to include four main elements:
- the arguments for the query, using parameters which will be covered in this tutorial
- the query itself
- the loop
- finishing off: closing if and while tags and resetting post data
In practice this will look something like the following:
<?php $args = array( // Arguments for your query. ); // Custom query. $query = new WP_Query( $args ); // Check that we have query results. if ( $query->have_posts() ) { // Start looping over the query results. while ( $query->have_posts() ) { $query->the_post(); // Contents of the queried post results go here. } } // Restore original post data. wp_reset_postdata(); ?>
The arguments are what tells WordPress what data to fetch from the database and it's those that I'll cover here. So all we're focusing on here is the first part of the code:
$args = array( // Arguments for your query. );
As you can see, the arguments are contained in an array. You'll learn how to code them as you work through this tutorial.
Coding Your Arguments
There is a specific way to code the arguments in the array, which is as follows:
$args = array( 'parameter1' => 'value', 'parameter2' => 'value', 'parameter3' => 'value' );
You must enclose the parameters and their values in single quotation marks, use =>
between them, and separate them with a comma. If you get this wrong, WordPress may not add all of your arguments to the query or you may get a white screen.
Status Parameters
As you'll know if you've ever converted a post's status from Draft to Published, or maybe put it in the trash, WordPress assigns a status to each post. You can use the post_status
parameter to query for posts with one or more statuses.
The arguments available are:
-
publish
: A published post or page. -
pending
: Post is pending review. -
draft
: A post in draft status. -
auto-draft
: A newly created post, with no content. -
future
: A post to publish in the future. -
private
: Not visible to users who are not logged in. -
inherit
: A revision. -
trash
: Post is in trashbin. -
any
: Retrieves any status except those from post statuses with'exclude_from_search'
set to true (i.e.trash
andauto-draft
).
If you don't specify a status in your query arguments, WordPress will default to publish
; if the current user is logged in, it will also include posts with a status of private
. If you run a query in the admin pages, WordPress will also include the protected statuses, which are future
, draft
and pending
by default.
So let's say that you're running an events site and you're using a custom post type of event, using the publication date as the date that the event takes place. By default WordPress won't display any events that haven't happened yet: although you've scheduled them, their scheduled date is in the future so their post status is future.
To get around this you simply use these arguments:
$args = array( 'post_type' => 'event', 'post_status' => 'future' );
This will only display those events which haven't happened yet, as those will have the publish
status. But if you also want to display events which have happened, you can use an array of post statuses to include more than one:
$args = array( 'post_type' => 'event', 'post_status' => array( 'future', 'publish' ) );
The post_status
parameter is essential when you're querying for attachments. This is because they have a status of inherit
, not publish
. So to query for all attachments, you'd use this:
$args = array( 'post_type' => 'attachment', 'post_status' => 'inherit' );
Alternatively you could replace inherit
with any
which would have the same effect.
Order Parameters
There are two parameters you use to order posts retrieved by WP_Query
: order
and orderby
. As you'd expect, order
defines the order in which posts will be output in the loop, and orderby
defines which field in the database they'll be sorted by.
Let's start by looking at the arguments for order
.
The order Parameter
There are just two arguments you can use for this:
-
ASC
: ascending order from lowest to highest values (1, 2, 3; a, b, c). -
DESC
: descending order from highest to lowest values (3, 2, 1; c, b, a).
These are fairly self-explanatory. If you don't include an argument for order
, WordPress will default to DESC
.
The orderby Parameter
You can sort your posts by a range of fields:
-
none
: No order (available with Version 2.8). -
ID
: Order by post id. Note the capitalization. -
author
: Order by author. -
title
: Order by title. -
name
: Order by post slug. -
type
: Order by post type. -
date
: Order by date. -
modified
: Order by last modified date. -
parent
: Order by post/page parent id. -
rand
: Random order. -
comment_count
: Order by number of comments. -
menu_order
: Order by Page Order. Used most often for Pages (using the value you add to the metabox in the Edit Page screen) and for Attachments (using the integer fields in the Insert / Upload Media Gallery dialog), but could be used for any post type withmenu_order
enabled. -
meta_value
: Sort by the value for a meta key (or custom field). This only works if you also include ameta_key
parameter in your arguments. Meta values are sorted alphabetically and not numerically (so 34 will come before 4, for example). -
meta_value_num
: Order by numeric meta value. As withmeta_value
, you must also include ameta_key
argument in your query. -
post__in
: Preserve post ID order given in thepost__in
array.
The default is date
, i.e. the date a post was published.
So for example if you want to sort your posts by title in ascending order, you would use these arguments:
$args = array( 'orderby' => 'title', 'order' => 'ASC' );
Ordering by Multiple Fields
You don't have to stick to just one field to sort your posts by. To sort by multiple fields, you use an array with the orderby
parameter and (optionally) with the order
parameter if you want to sort each field in a different order.
So let's say you have a ratings custom field which you want to use for sorting in an e-commerce site. You could sort by rating and then title, both in ascending order, this way:
$args = array( 'orderby' => array( 'meta_value_num', 'title' ), 'order' => 'ASC', 'meta_key' => 'rating' );
Note that I've included the meta_key
argument to let WordPress know which custom field I'm using. You do this because of the way WordPress stores post metadata: not in the wp_posts
table, but in the wp_postmeta
table.
But what if you wanted to order by rating in descending order and then title in ascending order? You simply use another array:
$args = array( 'orderby' => array( 'meta_value_num', 'title' ), 'order' => array( 'DESC', 'ASC' ), 'meta_key' => 'rating' );
You could also sort by multiple fields when not using post metadata, for example to sort by post type and then date:
$args = array( 'orderby' => array( 'type', 'date' ), 'order' => array( 'ASC', 'DESC' ) );
This would sort by post type in ascending order and then within each post type, by date in descending order.
Pagination Parameters
The next set of parameters we come to are for pagination. These help you define how many posts will be queried and how pagination will work when they are output.
The available parameters are:
-
nopaging
(boolean): Show all posts or use pagination. The default is'false'
, i.e. use pagination. -
posts_per_page
(int): Number of posts to show per page. -
posts_per_archive_page
(int): Number of posts to show per page—on archive pages only. -
offset
(int): Number of posts to displace or pass over. -
paged
(int): The page in the archive which posts are shown from. -
page
(int): Number of pages for a static front page. Show the posts that would normally show up just on page X of a Static Front Page. -
ignore_sticky_posts
(boolean): Ignore post stickiness—defaults tofalse
.
Let's take a look at some examples.
Number of Posts and Offsetting Posts
For example, to display the five most recent posts:
$args = array( 'posts_per_page' => '5' );
Or to display five recent posts excluding the most recent one:
$args = array( 'posts_per_page' => '5', 'offset' => '1' );
Note that although you're fetching posts from the most recent six posts in the database, you still use 'posts_per_page' => '5'
as that's the number of posts which will be output.
Taking this a bit further, you can write two queries: one to display the most recent post and a second to display ten more posts excluding that post:
$args = array( 'posts_per_page' => '1' ); // Query and loop go here as well as resetting posts. $args = array( 'posts_per_page' => '10', 'offset' => '1' ); // Second query, loop, and resetting go here.
You can also use posts_per_page
to display all posts:
$args = array( 'posts_per_page' => '-1' );
Sticky Posts
Normally your sticky posts will show up first in any query: if you want to override this, use ignore_sticky_posts
:
$args = array( 'posts_per_page' => '5', 'ignore_sticky_posts' => true );
The above arguments will return the most recent five posts regardless of whether they are sticky or not.
Note that if you want to display just sticky posts, you'll need to use the get_option()
function and the post__in
argument as follows:
$sticky = get_option( 'sticky_posts' ); $args = array( 'posts_per_page' => '5', 'post__in' => $sticky );
The above would display the last five sticky posts: if there are less than five (e.g. three) sticky posts, it won't display non-sticky posts but just the most recent three sticky posts.
Pagination in Archives
As well as defining how many posts are fetched from the database, you can also use pagination parameters to define how the resulting posts will be paginated on archive and search pages.
So for example on an archive page you could use this code to display 20 posts per page in the archive:
$args = array( 'posts_per_archive_page' => '20' );
Note: the posts_per_archive_page
argument will override posts_per_page
.
You can also choose to output just the pages which would appear on a given page in paginated pages. So for example if you wanted to show the 20 posts that would appear on the third page in the example above, you'd use this:
$args = array( 'posts_per_archive_page' => '20', 'paged' => '3' );
An alternative way to query the same posts would be to use the offset
argument:
$args = array( 'posts_per_page' => '20', 'offset' => '40' );
This skips the first 40 posts (which would be on the first two archive pages) and fetches the next 20 posts (which would be on the third archive page. One of the things I love about WordPress is how it so often gives you more than one way to achieve something!
You can also turn pagination off altogether, to ensure that all posts will show on the same page:
$args = array( 'nopaging' => true );
Summary
The WP_Query
class gives you plenty of flexibility when it comes to determining how many posts you want to query, what order you want to display them in, and what status of post you want to show.
Some of these arguments are essential for querying certain kinds of post (for example 'post_status' => 'inherited'
for attachments), while others simply give you more control over the way your queries run.
By using these parameters you can create custom queries that do a lot more than simply outputting the most recent published posts.
Comments