How To Use WordPress get_posts + Examples

WordPress get_posts has been a core function that many WordPress plugins use to retrieve posts from a WordPress database. With the get_posts function, you can specify which posts, pages, and custom post types, filters, and which order you want them to be. WordPress get_posts function is handy, especially when you want to build a list of posts in a particular section of your site. However, it can get confusing and daunting to use if you aren’t familiar with PHP or coding in general.

In this article, you will learn how to use it, some use cases/examples, and further specify the posts you are looking for. Without further ado, let’s get started.

What’s the difference between get_posts and get_pages?

It is essential to clarify the differences between these two WordPress functions – get_posts and get_pages. Both of them are used for the same reason: to retrieve posts from a WordPress database. However, some minute differences are vital to understand.

  • Parameter names and values differ between the two but act the same way regardless. It is just a matter of remembering the different names and values.
  • The get_pages function is less specific because it cannot retrieve posts based on the meta_key and meta_value parameters.
  • The get_pages function queries the database directly and returns an array of page objects you can then iterate over. It does not use wp_query.

Parameters of get_posts

Here is an example of how to use the WordPress get_posts function:

<?php

$args = [
    "posts_per_page"   => 5,
    "paged"            => 1
    "tax_query" => [
        [
            "taxonomy" => "category",
            "field"    => "slug",
            "terms"    => "videos,movies",
        ]
    ],
    "orderby"          => "post_date",
    "order"            => "DESC",
    "exclude"          => "1123, 4456",
    "meta_key"         => "",
    "meta_value"       => "",
    "post_type"        => "post",
    "post_status"      => "publish"
];

$posts_array = get_posts($args); 

There are plenty of parameters you can use that are not included in the above function. The function above only contains the most popular of the parameters.

  1. posts_per_page – Defines the number of posts returned; if you want all posts to be returned, use -1.
  2. paged – Using the posts per page argument, we may navigate between a series of posts. It’s a pagination tool. For example, if posts per page = 10 and the result contains 20 posts, assigning paged to 2 will return the last 10 posts.
  3. tax_query:– Takes an array of argument arrays that is used to query posts by an array of taxonomies.
  4. orderby – used to sort the returned posts. Values can be “meta_value”, “comment_count”, “none”, “date”, etc. This is very useful if you only want to order posts in a specific way, such as the most popular posts or most recent by date.
  5. order – defines the ascending or descending order of the “orderby” property. Values can be “ASC” for ascending and “DESC” for descending.
  6. exclude – defines the excluded posts to not return by taking in a comma-separated list of posts IDs.
  7. meta_key and meta_value – if you only provide a value to “meta_key”, then it will return posts with the matching “meta_key”. If you also provide a value to both “meta_key” and “meta_value”, then it will return posts that match both the “meta_key” and “meta_value”.
  8. post_type – retrieves content based on the value taken. By default, it’s “post.”
  9. post_status – retrieves post based on the status of the post. Possible values are “publish”, “pending”, “draft”, “future”, “trash”, or “any”.Examples of get_posts

WordPress get_posts function use cases

Now that you know the basic parameters of the WordPress get_posts function. It’s time to start learning how to implement get_posts into your website. Below is a list of code snippets that you can use as a reference for your use case.

<?php

$args = ['posts_per_page' => 10, 'orderby' => 'comment_count'];
$posts = get_posts($args);

foreach($posts as $post) {
    echo "<h1>" . $post->post_title . "</h1><br>";
    echo "<p>" . $post->post_content . "</p><br>";
} 

Notice that the “orderby” parameter is used to sort the posts based on the number of comments. And to display the most popular posts by comments, we set “posts_per_page”  to 10. It then prints out an HTML output by displaying the post title in a heading and the post content in a paragraph.

Posts with Matching Meta Key and Value

Sometimes, we want to retrieve posts based on a certain meta key and meta value. We can do that by using the meta_key and meta_value and setting the parameters to whatever we want to retrieve. In this case, the meta_key is “user_first_name” and the meta_value is “John”.

<?php

$args = [
    'post_type' => 'post',
    'meta_key' => 'user_first_name',
    'meta_value' => 'John'
];

$posts = get_posts($args);

Custom Post Type with Custom Taxonomies

Sometimes we have several custom post types in our WordPress database. But how can we retrieve this? And what if I want to get more specific? Custom taxonomies are a great solution to this since it allows you to be very specific with the posts you want to return. Here’s how you can use it:

<?php

$args = [
    'posts_per_page' => -1, 
    'post_type' => 'coupons', 
    'tax_query' => [
        [
             "taxonomy" => 'coupon_category',
              "field"    => 'slug',
              "terms"    => ['plugins', 'themes'],
        ]
    ]
];

$posts = get_posts($args);

The posts of a custom post type named “coupons” that belong to the “plugins” and “themes” custom taxonomies are being retrieved in this example.

Conclusion

WordPress get_posts is a powerful function that allows you to retrieve lists of posts from your WordPress database and display them anywhere on the frontend side of your WordPress website. Overall, you have now learned what the WordPress function get_posts is, what it does, how to use it, its different parameters, the possible values on these parameters, and different use cases for get_posts.

About The Author

Andriy Haydash

Andriy Haydash

Andriy Haydash is a WordPress Expert who helps people build and launch successful WordPress membership and e-learning websites.

Note: Not all of the articles are written directly by me.
Affiliate Disclaimer: Some links in the post may be my affiliate links

The Ultimate Managed Hosting Platform

Before YOU Leave...
Join My Newsletter

Get practical tips & tricks on how to start, grow and market your course/membership site.