WP_Query Arguments: Status, Order and Pagination

by:

Web Development

[ad_1]

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, and 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:

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:

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:

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: post in draft status
  • auto-draft: 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 trash bin
  • any: any status except those from post statuses with exclude_from_search set to true (i.e. inherit, trash and auto-draft). Any custom post statuses where you have set exclude_from_search to true will also be excluded from results.

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.

The inherit status applies to both attachments and revisions. Media files uploaded within the edit screen are attached to the current post the we are editing. Therefore it makes sense for them to have the same status as the parent post. Similarly, revisions to a post also use inherit as status because their status should be in sync with the parent post.

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:

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:

The post_status parameter is essential when you’re querying for attachments. Otherwise, you will get back an empty list. This is because they have a status of inherit, not publish. So to query for all attachments, you’d use this:

Alternatively you could replace inherit with any which would have the same effect. Here is what I get after running the above query.

You might be confused about the mismatch in post status specified in our query and the retrieved results. This is happening because attachments return the post status of their parents. In this case, all those posts happen to be published.

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. You can also pass an array to create multiple order/orderby pairs for sorting.

The orderby Parameter

You can sort your posts by a range of fields:

  • none: no order
  • 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 or page parent id
  • rand: random order
  • comment_count: order by number of comments
  • relevance: order by search terms. Priority is given to full sentence matches. After that we move on to all search terms in the title, some search terms in the title and search terms in the post
  • 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 Media Gallery dialog), but could be used for any post type with menu_order enabled
  • meta_value: sort by the value for a meta key (or custom field). This only works if you also include a meta_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 with meta_value, you must also include a meta_key argument in your query
  • post__in: preserve post ID order given in the post__in array
  • post_name__in: preserve post slug order given in the post_name__in array
  • post_parent__in: preserve post parent order given in the post_parent__in array

The last two options are available since WordPress 4.6. Keep in mind that the value of the order parameter is ignored when you use post__in, post_name__in and post_parent__in options. 

The default is date, ie. 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:

Posts Ordered by TitlePosts Ordered by TitlePosts Ordered by Title

The first post will seem out of place to you. The reason it is out of order is because it is a sticky post and sticky posts come at the start of the list because a pagination parameter ignore_sticky_posts is set to false by default.

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 or a list of blog posts. You could sort by rating and then title, both in descending order, this way:

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.

The above arguments will sort all the posts first by their rating scores in descending order and then the posts with the same rating score will be sorted by their titles in descending order.

Top Rated Posts (Descending Title Order)Top Rated Posts (Descending Title Order)Top Rated Posts (Descending Title Order)

But what if you wanted to order by rating in descending order and then title in ascending order? You simply use another array:

Top Rated Posts (Ascending Title Order)Top Rated Posts (Ascending Title Order)Top Rated Posts (Ascending Title Order)

You could also sort by multiple fields when not using post metadata, for example to sort by post type and then date:

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', ie. 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 to false

Let’s take a look at some examples.

Number of Posts and Offsetting Posts

For example, to display the five most recent posts:

Five Most Recent PostsFive Most Recent PostsFive Most Recent Posts

We will automatically get the five most recent posts because the value of orderby parameter is set to date by default as we learned in the previous section. Again, you might have noticed that the sticky post stays at the top even if it is not the most recent. It also takes up one spot within our five posts. You can tell WordPress to ignore sticky posts as we will see below.

Or to display five recent posts excluding the most recent one:

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:

You can also use posts_per_page to display all posts:

Sticky Posts

Normally your sticky posts will show up first in any query: if you want to override this, use ignore_sticky_posts:

The above arguments will return the most recent five posts regardless of whether they are sticky or not.

Five Most Recent Posts (No Sticky)Five Most Recent Posts (No Sticky)Five Most Recent Posts (No Sticky)

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:

The get_option() function will return an array of sticky post IDs which are passed to the post__in parameter. The above would display the last five sticky posts. If there are less than five (eg. 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:

Note: the posts_per_archive_page argument will override posts_per_page on all pages where is_archive() and is_search() return true.

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:

An alternative way to query the same posts would be to use the offset argument:

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:

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.

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 time working on personal projects that make his everyday life easier or taking long evening walks with friends.

Leave a Reply

Your email address will not be published. Required fields are marked *