Exploring the WordPress get_posts Function
Share:
Free JavaScript Book!
Write powerful, clean and maintainable JavaScript.RRP $11.95
Many WordPress plugins retrieve posts from the database by customizing the sorting order, retrieving posts based on a specific meta key or taxonomy. Have you ever wondered how these plugins retrieve customized lists of posts without writing any SQL queries? In this tutorial we’ll learn how to do exactly that.
In this article we’ll explore the get_posts()
function with some examples of how to use it in your own projects. We’ll also cover some typical use cases for this function and how it’s different from the WP_Query
object and get_pages
function.
What is the get_posts()
Function?
The get_posts
function has been available in WordPress core since WordPress 1.2.0. This function is basically used to retrieve posts from the database by applying custom filters and sorting the final result based on a set of parameters.
The get_posts()
function returns an array of WP_Post
objects. Each WP_Post
object represents an individual post.
Internally get_posts
uses the WP_Query
object to construct and execute the SQL queries based on the passed set of parameters.
Note: Posts means post, page and custom post type.
Why Not Use the WP_Query
Object Directly?
Plugins use get_posts
function instead of WP_Query
object because using the WP_Query
object directly alters the main loop (i.e., the global $wp_query
variable) which would cause site issues.
What Is the Difference Between get_posts()
and get_pages()
Functions?
Both of them are used to retrieve posts from the WordPress database, however, here are some of the differences between them:
- Several of the parameter names and values differ between them. Although they behave the same way regardless of the names of the parameters.
- The
get_pages()
function currently does not retrieve posts based onmeta_key
andmeta_value
parameters. - The
get_pages()
function doesn’t use theWP_Query
object. Instead, it constructs and executes SQL queries directly.
get_posts()
Function Parameters
The get_posts
function takes only one argument as an array. The array contains the different parameters to apply custom filters and sort the result.
Here’s a code example which shows how to call this function and the various parameters available:
<?php
$args = array(
"posts_per_page" => 5,
"paged" => 1
"tax_query" => array(
array(
"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 more parameters available, but these are the most commonly used ones. Let’s look at each of these parameters:
- posts_per_page: This parameter defines the number of posts to return. Use -1 if you want all the posts.
- paged: Allows us to navigate between a set of posts while using the
posts_per_page
parameter. It is used for pagination. For example: supposeposts_per_page
is 10 and there are 20 posts in the result, then if you assignpaged
to 2 then last 10 posts are returned. - tax_query: Display posts of a particular taxonomy slug i.e., filter out posts of the other taxonomy slug.
terms
can take a comma separated string representing multiple taxonomy slugs. - orderby: It’s used to sort the retrieved posts. Some possible values are: “none”, “date”, “rand”, “comment_count”, “meta_value”, “meta_value_num” etc. While sorting using “meta_value” and “meta_value_num” you need to provide the
meta_key
parameter. - order: Designates the ascending or descending order of the
orderby
parameter. Possible values are “DESC” or “ASC”. - exclude: It takes a comma separated list of post IDs which will be excluded from a database search.
- meta_key and meta_value: If you provide only
meta_key
, then posts which have the key will be returned. If you also providemeta_value
then posts matching themeta_value
for themeta_key
is returned. - post_type: Retrieves content based on post, page or custom post type. Remember that the default
post_type
is only set to display posts but not pages. - post_status: Retrieves posts by status of the post. Possible values are: “publish”, “pending”, “draft”, “future”, “any” or “trash”.
The WP_Post
Object
The get_posts
function returns an array that contains WP_Post
objects. Here are the important properties of the WP_Post
object:
- ID: ID of the post
- post_author: Author name of the post
- post_type: Type of the post
- post_title: Title of the post
- post_date: Date on which post was published. Format: 0000-00-00 00:00:00
- post_content: Content of the post.
- post_status: Status of the post
- comment_count: Number of comments for the post
Examples of get_posts
Let’s check out some examples using the get_posts
function.
Most Popular Posts
If you want to display the top n number of the most discussed posts on your site, then you can use get_posts
to retrieve them. Here’s an example:
<?php
$args = array("posts_per_page" => 10, "orderby" => "comment_count");
$posts_array = get_posts($args);
foreach($posts_array as $post)
{
echo "<h1>" . $post->post_title . "</h1><br>";
echo "<p>" . $post->post_content . "</p><br>";
}
?>
Here, we are using the orderby
parameter to sort the posts based on the number of comments, retrieving the top 10 posts.
Random Posts
You can also easily retrieve random posts. This is helpful to recommend users another article on your site once they’ve finished reading the current one. Here’s the code for this:
<?php
$args = array("posts_per_page" => 1, "orderby" => "rand");
$posts_array = get_posts($args);
foreach($posts_array as $post)
{
echo "<h1>" . $post->post_title . "</h1><br>";
echo "<p>" . $post->post_content . "</p><br>";
}
?>
In the above example, we passed the value rand
to the order_by
parameter.
Posts with Matching Meta Key and Value
We might want to retrieve all posts which have a particular meta key and value assigned. For example: some blogs have a reviewer for every article. We might want to retrieve articles reviewed by a particular reviewer.
Here is the code to do just that:
<?php
$args = array("posts_per_page" => -1, "meta_key" => "reviewer", "meta_value" = "narayanprusty");
$posts_array = get_posts($args);
foreach($posts_array as $post)
{
echo "<h1>" . $post->post_title . "</h1><br>";
echo "<p>" . $post->post_content . "</p><br>";
}
?>
Here, we’re retrieving all the posts reviewed by “narayanprusty”. We’re assuming the reviewer name is stored via the meta key “reviewer” for every post.
Custom Post Type with Custom Taxonomy
We may want to retrieve posts of a custom post type with a custom taxonomy name. Consider this code example:
<?php
$args = array("posts_per_page" => -1, "post_type" => "coupons", "tax_query" => array(
array(
"taxonomy" => "coupon_category",
"field" => "slug",
"terms" => "plugins,themes",
)
));
$posts_array = get_posts($args);
foreach($posts_array as $post)
{
echo "<h1>" . $post->post_title . "</h1><br>";
echo "<p>" . $post->post_content . "</p><br>";
}
?>
In this example, we’re retrieving the posts of a custom post type named “coupons” which belong to the “plugins” and “themes” custom taxonomies.
Conclusion
In this article we saw how the get_posts
function works, the various parameters it supports, looping through the returned result and some sample use cases. The get_posts
function is one of the most used WordPress functions, I hope you can now start using it your own projects.
New books out now!
Get practical advice to start your career in programming!
Master complex transitions, transformations and animations in CSS!
Latest Remote Jobs




