How to Use the WordPress get_posts Function: A Guide to Building Post Lists

The WordPress get_posts function allows developers to retrieve post data from the WordPress database by taking the ID of a given post and returning the corresponding piece of content from the database. Basically, with the get_posts* function, you can choose from an array of WP_Post objects the exact post, page, or custom post type you want to retrieve.

(*Note: posts, pages, and custom post types all fall in the category of post in this article.)

There are a number of WordPress plugins that retrieve posts from the WordPress database by customizing the sorting order, and then retrieving posts based on specific meta or taxonomy.

In this article, we will go over how you can do just that – learn the necessary PHP/MySQL to use the get_posts function like a coding professional. After reading this article, you’ll know how to specify in detail the exact post you need, receive a custom results set, and be able to filter and arrange the items in any order you wish.

Don’t worry if you don’t have much PHP/MySQL experience! Together we’ll go over the basics of what you need to know in order to use the get_posts function to build queries based on a number of different parameters.

This comprehensive guide will help you learn how to use the WordPress get_posts function

What is the WordPress get_posts Function?

The get_posts function has been a part of the WordPress core since the 1.2.0 version. You can apply custom filters, taxonomy, and other parameters to sort the items of the resulting list.

As we mentioned, get_posts retrieves an array of WP_Post objects, and each of those objects stands for a particular post. To do this, get_posts internally uses the WP_Query object (which we’ll also go over) to build and execute simple or advanced SQL queries based on the parameters you establish.

The arrays you can create and retrieve using the get_posts function are quite useful, as they allow you to pass large sections of data at a given time. While they may seem a bit challenging to understand at first, we’ll go over how the array is structured, set up, and laid out. In the end, you’ll see that they’re quite simple!

Why You Shouldn’t Use the WP_Query Object without get_posts

While the get_posts function uses the WP_Query object, we don’t recommend using WP_Query directly. This is because the WP_Query object directly alters the main loop, that is, the $wp_query variable, which may cause problems with your website.

Using the get_post function over the WP_Query object makes sure that the loop doesn’t get altered, as it automatically resets the main loop – something you may forget to do if using WP_Query directly – and so eliminates the possibility of issues on your site.

This is also why plugins use get_posts rather than the WP_Query object directly.

What’s the Difference between get_posts and get_pages?

While both the get_posts and get_pages functions work by retrieving posts from your WordPress database, there are some differences that make get_posts a preferable option.

Here are a few differences:

  1. The names of parameters and values differ between the two functions, although they can be tweaked to work in a similar fashion. The get_posts function parameters are easier to use and more intuitive.
  2. Unlike get_posts, the get_pages function doesn’t retrieve posts based on meta_value and meta_key parameters.
  3. Unlike get_posts, the get_pages function doesn’t use the WP_Query object. Rather, it directly constructs and executes SQL queries.

How Does the WordPress get_posts Function Work?

Before we delve further into how you can use the WordPress get_posts function, let’s first see how it works and what the different parameters are comprised of.

There are two parts to using get_posts:

  • Building a custom query. 

The first step to using get_posts is creating your custom query by defining a number of parameters (values) and uploading them to the get_posts function. It won’t look like a MySQL query, and you won’t need to write select statements, but WordPress will automatically convert the array of parameters into a real, secure MySQL query. Then, it will run the query against the database, and retrieve the specified array of posts.

  • Traversing the result set. 

The second step is basically iterating (going through each portion of data in your array) the results set retrieved by get_posts with the use of a foreach cycle.

Before we go into how you can build a custom query, let’s first take a look at the different parameters and values you’ll need to define to use get_posts and WP_Query. Then, we’ll go over how you can use them!

Parameters Used for the get_posts Function

As we’ve mentioned, get_posts uses the WP_Query object to return post items, keeping them in an array based on the parameters you set up in the get_posts function and in the WP_Query object. There are a lot of parameters you can adjust, and a lot of variables you can fine-tune for more complexly defined custom queries.

If we were to roughly group the different parameters, then they all fall under one of the following 15 general categories:

  1. Author Parameters
  2. Category Parameters
  3. Date Parameters
  4. Post & Page Parameters
  5. Password Parameters
  6. Post Type Parameters
  7. Tag Parameters
  8. Taxonomy Parameters
  9. Search Parameters
  10. Order & Orderby Parameters
  11. Custom Field, i.e. Post Meta Parameters
  12. Permission Parameters
  13. Mime Type Parameters
  14. Caching Parameters
  15. Return Fields Parameters

This general list of parameter types can help you understand which categories you can tweak and define to guide your get_posts array for optimal results.

Let’s look at some specific examples of what the most commonly used parameters look like and represent. You’ll probably end up using at least some of them when you’re setting up the array for your get_posts function.

Most commonly used parameters include:

    • posts_per_page
      By defining the posts_per_page value, you can set the number of posts the function should return. If you want the get_posts function to return all posts, you can use -1.
    • paged
      The paged parameter is how you can navigate between the pages of your posts sets. Once you’ve used the post_per_page function, paged allows you to navigate to the exact page of posts you want. For instance, if you set the value of posts_per_page to 5, and the resulting set contains 15 posts, you can set the value of paged to 3 if you want to retrieve the last 5 posts, i.e., access the third page of results.
    • tax_query
      The tax_query parameter display posts based on a specific taxonomy slug. It basically filters out the posts of the other taxonomy slugs. You can also use terms and take a string separated by commas to represent various taxonomy slugs.
    • orderby
      This function allows you to sort the order of returned posts. For instance, values you can use to define this parameter include: date, rand, comment_count, and none. Other options are meta_value and meta_value_num, but to use those you’ll also need to define the meta_key parameter.
    • order
      Once you’ve defined the orderby parameter and specified according to what value the retrieved posts should be ordered, order allows you to decide whether the results should be displayed in ascending or descending order. The two values you can use are ASC for ascending, and DESC for descending order.
    • exclude
      Based on a comma-separated list of post IDs, the exclude parameter will exclude this list from the database search.
    • meta_key and meta_value
      The meta_key parameter returns posts that contain the specified key. Defining the meta_value as well, further filtering the results, you’ll get posts that match the meta_value for the specified meta_key.
    • post_type
      As we mentioned, the get_posts function retrieves posts, pages, or custom post types. But under the post_type value, you get to specify what type of content you want retrieved: post, page, or custom post type. The default value of post_type displays only posts, and not pages. You should take care to change this if you want to also retrieve pages.
    • post_status
      The post_status parameter allows you to specify which posts you want to retrieve based on their status. This is a great and easy way to access all your published posts at once. Some possible values you can use to specify the post_status include publish, draft, pending, any, future, or trash.

Before we give you some examples of the get_posts function, let’s look at some properties of the WP_Post object, based on which the get_posts function returns a specific array of objects. You’ve already seen some of these in the previous list of parameters.

Some of the most important properties of the WP_Post object include:

  • ID
    Specified the ID of the post.
  • post_author
    This value specifies the name of the post’s author.
  • post_type
    Specifying the post_type (post, page, or custom post) can help you retrieve it based on that parameter when you use the get_posts function.
  • post_title
    This is the title of the post. If you’re trying to create an array based on meta_key later with the get_posts function, having defined this value will make things a lot easier.
  • post_date:
    This value specifies the date and time on which the post was published. If you fail to specify it, WordPress fills it automatically with the current date and time. The format required is yyyy-mm-dd hh-mm-ss.
  • post_content
    This parameter specifies the content of the post.
  • post_status
    This is the status of the post, i.e. if it’s published, a draft, trash, pending, future, and so on.
  • comment_count
    Specifies the number of comments on the particular post.

As you can see, once you specify the values for the WP_Post objects, retrieving them based on one or more parameters using the get_posts function is super easy!

Next, we’ll go over how you can use parameters to get simple and more complex queries, as well as retrieve desired posts based on these parameters. We’ll do this by looking at some comprehensive examples.

The get_posts PHP function will allow you to build custom lists of posts

How to Build Queries with get_posts On WordPress

We’ve been focusing on the technicalities of the get_posts function, so it may still feel quite abstract. To give you a better sense of what we’re doing, let’s unpack the process and start off with an example of a get_posts code:

$args = array(“posts_per_page” => 5, “orderby” => “comment_count”);
$posts_array = get_posts($args);
foreach($posts_array as $post)

. $post->post_title .


. $post->post_content .


In this example, we’ve adjusted the get_posts function to give us 5 posts per page by setting the value after posts_per_page to 5, and to order them by comment count, by specifying that value after orderby. The latter bit, foreach, is the code used to retrieve the query, and we’ll get into it more later in the article.

You can manipulate any of the parameters to customize your search. Let’s look at how you can do this to create simple and complex queries.

Adjusting the Parameters to Build Simple Queries

We gave you an overview of the 15 general categories that the different WP_Post objects fall into. Each category contains numerous objects that allow you to further specify your search, and we already provided some examples in the list of the most commonly used parameters.

Let’s look at the category of author to showcase how you can use the various underlying categories to build a simple query.

The author category, which allows you to retrieve posts based on their author, includes the following parameters:

    • author (int) 
      Specifies the author ID.
    • author_name (string)
      This is a string where you can define the author’s name with in a user_nicename format.
    • author__in (array) – an array of multiple authors’ IDs
      An array that contains multiple authors’ IDs – allows you to retrieve multiple IDs at once by implementing commas.
    • author__not_in (array)
      An array that allows you to exclude multiple authors’ IDs from the result set. Again, you can use commas to specify the authors you don’t want included in the search.

Let’s look at an example of how you can use one of these parameters to build a query.

$my_posts = get_posts( array( ‘author’ => 3 ) );

Here, we’ve simply specified that we want to retrieve posts from the author whose ID is the value 3.

You can use the same object to create an array of authors whose posts you want to retrieve, like so:

$my_posts = get_posts( array( ‘author’ => ‘3,7,13’ ) );

In this query, we’ve specified that we want to see the posts from an array of authors, namely those with the corresponding IDs of 3, 7 and 13.

If you want to exclude a single author from the query, you can use the same object and adjust the value to include a negative before the author’s ID. For instance:

$my_posts = get_posts( array( ‘author’ => 4 ) );

Here, we’ve specified that we want to see the posts of all authors except the author with the ID value 4 by adding a negative () before the value.

If you want to exclude multiple authors’ posts from the query, you can do so by using the author__not_in array and placing commas before the author IDs, like so:

$my_posts = get_posts( array( ‘author__not_in’ => array( 2, 6, 11 ) ) );

The posts that will be retrieved will not include those created by the authors with the ID values of 2, 6 and 11.

Alternately, if you want to create a specific array of authors whose posts you do want to retrieve, you can use the author_in object. For instance:

$my_posts = get_posts( array( ‘author__in’ => array( 2, 6, 11 ) ) );

This code means that the array will include specifically the posts of the authors with the ID values of 2, 6 and 11.

There are multiple objects in each of the 15 categories that you can use to navigate the desired results as you create a query. Applying some of them, like the author parameters, is quite easy. However, this isn’t true of all parameters – some need more attention and detail. But don’t worry! We’ll go over this too, and once you get the hang of it, it won’t seem that complicated at all.

While at times this much information, or specification, will be enough, other times you will want to build more advanced queries so you can get the exact result set you want. Delving deeper into building queries will allow you to design them to retrieve posts based on the types of posts, custom taxonomies, and any other specific fields (objects) you want to use. Basically, building more advanced queries allows you to retrieve posts based on very exact specifications in a single query.

Excited? Not really, but you want to know how to do this anyway? We’ll take it. Let’s keep moving!

Adjusting the Parameters to Build Complex Queries

First off – don’t be intimidated by the word “complex” – it just means we’ll go over how you can use multiple parameters to build a custom query. We looked at how you can retrieve posts from, say, a certain author based on a single parameter – their author ID. Well, now we’ll look at how you can retrieve posts from, for instance, a certain author, on a certain date, in a certain order, with a certain status, and so on.

Let’s look at an example. Say you have a post type called album and a custom taxonomy name called genre. Assume you want to retrieve all posts from the prog-rock genre, in a certain order.

  • name: album
  • custom taxonomy name: genre
$show_albums = get_posts( array(
     ‘posts_per_page’ => 7,
     ‘orderby’    => ‘date’,
‘order’ => ‘DESC’,
     ‘post_type’  => ‘albums’,
     ‘genre’      => ‘prog-rock’,
     ‘post_status’ => ‘publish’
) );

This text uses the get_posts function to retrieve all albums (post_type), in the prog-rock genre (genre is a predefined custom_taxonomy_name), give you 7 posts per page (posts_per_page), order them by date (orderby), in descending order, starting with the latest post (order), and all the posts that will appear should fall in the published category (post_status).

So in this example, we retrieved posts with a certain taxonomy, based on genre, date, and post status.

But let’s take a step back and slowly progress through the levels of advanced queries. Here’s a simple way to retrieve all prog-rock albums (post types) from the genre custom taxonomy. Here is what the array of arguments would look like:

$args = array(
‘post_type’ => ‘album’,
‘tax_query’ => array(
‘taxonomy’ => ‘genre’,
‘field’ => ‘slug’,
‘terms’ => ‘prog-rock’

The code instructs the get_posts function to retrieve all the albums in the prog-rock genre (custom_taxonomy_name).

The next step is building a more complex array of arguments. To do this, we add the tax_query parameter, which basically creates an array of arrays or an array of argument arrays. This allows us to build advanced, complex queries on the basis of multiple taxonomies, like we showed you can do in the first example of this section.

$args = array(
‘numberposts’ => 15,
‘post_type’ => ‘album’,
‘relation’ => ‘AND’,
‘tax_query’ => array(
‘taxonomy’ => ‘genre’,
‘field’ => ‘slug’,
‘terms’ => ‘prog-rock’
‘taxonomy’ => ‘album_composer’,
‘field’ => ‘term_id’,
‘terms’ => 7

As you can see, we’ve added a tax_array under the original array command in order to build an array of additional taxonomy argument arrays. So, what do all these parameters mean?

First, we used the parameters to retrieve a list of the latest 15 album post types which fall in the prog-rock custom taxonomy name genre, which were composed by the album_composer with the term_id value of 7 (under terms). The parameter marked as relation sets the logical relationship between each inner taxonomy array when there are multiple arrays (as in this case).

We set the relation to AND, so we will retrieve all albums that satisfy both arrays – all albums that fall under the prog-rock genre AND are composed by album_composer number 7.

Another possible value of the relation parameter is OR. If we had inserted OR rather than AND, we would get a list of albums that were either in the prog-rock genre OR composed by album_composer with the ID value 7.

Building Meta Queries with Custom Field Parameters

Another cool way you can use the get_posts WordPress function is to build lists of posts using custom field parameters. You can do this by adjusting the meta_key and meta_value parameters in the query.

Here’s a simple example:

$args = array(
‘post_type’ => ‘album’,
‘meta_key’ => ‘year_released’,
‘meta_value_num’ => ‘1990’,
‘meta_compare’ => ‘<‘

In this query, we were able to use parameters using custom field key and value.

Basically, we retrieved all album post types based on year of release (meta_key) that were released before 1990 (meta_value_num). Note that here we didn’t simply use meta_value, which we could have had the value had been something like genre. Instead, we used meta_value_num as we are using a number-based value to retrieve the posts. The meta_compare parameters set the relationship between the meta_key and the meta_value. As we have set it to less than, i.e. <, the retrieved posts will be of albums released before 1990.

The default value of meta_compare is = (equal to). If we hadn’t specified the value or had indeed set it to =, we would have retrieved a list of all albums released in 1990. Other possible values for meta_compare are: ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘NOT EXISTS’, ‘REGEXP’, ‘NOT REGEXP’ and ‘RLIKE’. (You can get a full list of all the different taxonomy parameters here.)

Let’s expand this custom query a bit further. The next query will ask specifically for prog-rock albums that were released before 1990.

$args = array(
‘post_type’ => ‘album’,
‘meta_key’ => ‘year_released’,
‘meta_value_num’ => 1990,
‘meta_compare’ => ‘<‘,
‘tax_query’ => array(
‘taxonomy’ => ‘genre’,
‘field’ => ‘slug’
‘terms’ => ‘prog-rock’

As you can see, we’ve specified that we want to retrieve all albums in the prog-rock genre that were released before the year 1990.

With a bit more work, there’s no end to how much you can customize your queries using the get_posts function. To give you an idea of the specificity with which you can build complex custom queries, let’s expand the previous example even further. Here, we will query a post type with a custom taxonomy and two custom fields (by using meta_query).

$args = array(
‘post_type’ => ‘album’,
‘tax_query’ => array(
‘taxonomy’ => ‘genre’,
‘field’ => ‘slug’
‘terms’ => array( ‘prog-rock’ )
‘meta_query’ => array(
‘relation’ => ‘AND’,
‘key’ => ‘year_released’,
‘value’ => 1990,
‘type’ => ‘numeric’,
‘compare’ => ‘<‘,
‘key’ => ‘price’,
‘value’ => array( 10, 30 ),
‘type’ => ‘numeric’,
‘compare’ => ‘BETWEEN’,

Here, we’ve set arrays of parameters in order to get a list of prog rock albums released before 1990 with a price between $10 and $30.

We have the two custom fields based on year of release and album price under the meta_query. Like the tax_query parameter, meta_query allows us to build an array of array arguments. As the parameters that follow are already grouped under the meta_query object, we don’t need to put meta again before key, value, compare, and so on.

Using the Foreach Cycle to Traverse the Result Set

The last thing you should add to the code is a foreach cycle in order to retrieve a posts list.

Here’s an example of what it looks like:

$args = array(
‘numberposts’ => 10,
‘post_type’ => ‘album’,
$my_posts = get_posts( $args );
if( ! empty( $my_posts ) ){
$output = ‘<ul>’;
foreach ( $my_posts as $p ){
$output .= ‘<li><a href=”‘ . get_permalink( $p->ID ) . ‘”>’ 
. $p->post_title . ‘</a></li>’;
$output .= ‘<ul>’;

Basically, we’ve used this query to retrieve the last 10 album post types. The foreach cycle at the end completes the command, and returns a list of results.

And that’s all! Now you’re familiar with the basics of how you can use the WordPress get_posts function in order to build queries and retrieve lists of posts!

View Related Articles

How to Add a Favicon

Back in 1999, the favicon was introduced to Internet Explorer to help users tell bookmarked pages apart. Bookmarked pages used to be called “favorites”. And if you join this word with the word “icon”, you get a favicon.

How to Find Who Hosts a Website

Maybe someone else set up your website years ago and you can’t for the life of you remember who’s hosting it. You can’t find anything in your email, and you’ve lost the password to your other email back in the early 2000s.

Spam on Contact Pages

Running a website brings joys and woes, as do most things in life. There’s all the fun stuff – setting the website up, creating a blog, communicating with clients, turning a profit – and then there’s the stuff we could really do without, but is there nonetheless. Things that all website owners have to deal with, sooner or later. Things like spam on contact pages.

2 thoughts on “How to Use the WordPress get_posts Function: A Guide to Building Post Lists”

  1. Thanks for a great article. I was able to use get_posts() and a foreach loop to generate an unordered list of links using the_permalink & the_title for a CPT that I’m including on single-cpt.php to link to each of the CPTs. However, I can’t figure out how to add a class to the link of the current cpt by identifying which cpt I’m on.
    I have single-cpt-1.php, single-cpt-2.php, single-cpt-3.php and single-cpt-4.php and the list of links renders on each. If I’m on single-cpt-2.php I’d like to style that link differently than the others. Is this possible using get_posts?

Leave a Comment

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