WordPress
Article

Exploring the WordPress get_posts Function

By Narayan Prusty

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.

XML-RPC for WordPress

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 on meta_key and meta_value parameters.
  • The get_pages() function doesn’t use the WP_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:

  1. posts_per_page: This parameter defines the number of posts to return. Use -1 if you want all the posts.
  2. paged: Allows us to navigate between a set of posts while using the posts_per_page parameter. It is used for pagination. For example: suppose posts_per_page is 10 and there are 20 posts in the result, then if you assign paged to 2 then last 10 posts are returned.
  3. 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.
  4. 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.
  5. order: Designates the ascending or descending order of the orderby parameter. Possible values are “DESC” or “ASC”.
  6. exclude: It takes a comma separated list of post IDs which will be excluded from a database search.
  7. meta_key and meta_value: If you provide only meta_key, then posts which have the key will be returned. If you also provide meta_value then posts matching the meta_value for the meta_key is returned.
  8. 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.
  9. 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:

  1. ID: ID of the post
  2. post_author: Author name of the post
  3. post_type: Type of the post
  4. post_title: Title of the post
  5. post_date: Date on which post was published. Format: 0000-00-00 00:00:00
  6. post_content: Content of the post.
  7. post_status: Status of the post
  8. comment_count: Number of comments for the post

Examples of get_posts

Let’s check out some examples using the get_posts function.

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.

  • http://coderexample.com Arkaprava Majumder

    what are the issues you mentioned, “which would cause site issues”

    • http://qnimate.com/ Narayan Prusty

      Hi,

      When you make an request to WordPress to fetch a post, archive etc then WordPress uses the global $wp_query object to construct the query to fetch the resource. So if you make changes to this object then the resource that’s fetched will be different. Therefore you shouldn’t touch this object anyhow.

      • http://coderexample.com Arkaprava Majumder

        Thanks for the explanation.

  • Przemek Załużny

    “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.”

    You can use objects of type WP_Query class as many times as you like. For example (the last two lines of get_posts):

    $get_posts = new WP_Query;
    return $get_posts->query($r);

    I think it would be better to use “the global instance (object) of the WP_Query class” or just $wp_query instead of “WP_Query object”.

    To be honest the paragraph is a bit strange for me. I would rather compare get_posts with query_posts instead of WP_Query or $wp_query. I think it would be more natural.

  • http://portal2web.biz Joseph Levin

    I have a simple category setup on a site I’ve been working on- 3 categories that are children of a parent category.

    If there any way, using get_posts, to query the parent category so that each child category is displayed in ASC order, but the actual posts within each child category are displayed in DESC order?

    Thank you very much for your help!

  • Elmiro

    Hi,

    using the meta_key I receive no value.

    All the rest works perfectly. thanks for sharing.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Instant Website Review

Use Woorank to analyze and optimize your website to improve your website to improve your ranking!

Run a review to see how your site can improve across 70+ metrics!

Get the latest in WordPress, once a week, for free.