WordPress Get_Posts – Easy Guide To Using This Function

WordPress Get_Posts - Easy Guide To Using This FunctionAs you learn more about WordPress and begin to develop custom pages with it, one feature that you often have to use is the WordPress get_posts function.

This powerful function does just as the name indicates. It enables you to retrieve posts from the database, which you can then display on a page.

Beyond posts, it is interesting to know that anything stored in the wp-posts table can be retrieved using this function. This includes pages and custom post types.

There are many scenarios where you would need to use this function. For example, let’s say you want to create a page that displays all posts with the category “WordPress Tutorials”. You can quite easily do this with WordPress get_posts function.

But how?

In this article, we will show you how this function works, and how you can use it to retrieve and display posts, pages, and custom types.

Let’s get started.

Content:

  1. When to use get_posts
  2. How get_posts works
  3. Overview of get_posts parameters
  4. Retrieving posts with get_posts
  5. Display posts with WordPress get_posts function
  6. Conclusion

When to use get_posts

WordPress core provides different methods for developers to manipulate the wp_post table. The get_posts function is one of the methods available. Here are some use cases for the WordPress function.

If your WordPress site has multiple authors and you need to build a custom page for each author, then the get_posts function can be a handy tool to easily achieve this.

Secondly, the function provides an easy way to display posts on specific pages or if you want to filter posts by category. Also, you can perform advanced queries using custom taxonomies or custom post types.

How get_posts works

In WordPress, get_posts is a PHP function that can be used to retrieve posts (posts, pages, and custom post types) from the database based on certain query parameters.

You can apply custom filters, taxonomies, and other parameters to control the results from the query. This function takes one argument which is an array of parameters you wish to query the database for.

$args = array(
#some parameters
)
post_list = get_posts($args);

The code above shows the basic usage of this function. The $args variable is used to define the set of parameters and filters such as post_status, taxonomy (category or tags), post type, etc.

This variable is then passed as a parameter when you call the get_posts function.

The get_posts function returns an array of WP_Posts objects which you can loop over to display the posts on a page on your website. In the next section, we will show you how to retrieve posts using this function.

Overview of get_posts Parameters

Before we show you how to retrieve posts from the wp_posts table using this function, let us first go over all the parameters available for building custom queries.

Depending on the type of query you intend to build, you may have to use one or some of the parameters below.

  • Author Parameters
  • Category Parameters
  • Date Parameters
  • Post & Page Parameters
  • Password Parameters
  • Post Type Parameters
  • Tag Parameters
  • Custom Taxonomy Parameters
  • Search Parameters
  • Order & Orderby Parameters
  • Custom Field Parameters, i.e. Post Meta Parameters
  • Permission Parameters
  • Mime Type Parameters
  • Caching Parameters
  • Return Fields Parameters

The list above contains the 15 query parameters provided by WordPress core, however, you may not always use them all.

Commonly Used Query Parameters

Here are some commonly used parameters for building custom queries.

‘numberposts’

This parameter specifies the number of post objects to retrieve from the custom query. By default, the function retrieves the 5 most recent posts. If you use -1, the function will retrieve all the posts from your database. In the example below, we want the query to return 15 posts.

$args = array(‘numberposts’ => 15)

‘post_type’

This lets you choose the type of content to retrieve from your custom query. The function supports posts, pages, or custom post types. The default value is ‘post’ which will pull your blog posts. In the example below, we want to retrieve pages instead.

$args = array(‘post_type’ => ‘page’)

‘order_by’

This parameter lets you choose how to sort the result from your query. The values you can use for this parameter include the date, rand, comment_count, and none. There are advanced filtering parameters you can use as well such as meta key (meta_key) and meta value (meta_value).

‘order’

This works together with the order_by parameter. After choosing the sorting parameter, you can use ‘order’ to specify how the result is displayed. The options available include ASC (ascending order) and DESC (descending order).

$args = array(‘order_by’ => ‘comment_count’, ‘order’ => ‘ASC’)

‘category’

This parameter lets you choose a category for the post to filter content from. It takes an ID or a list of category IDs separated using a comma.

$args = array(‘category’ => 1)

‘include’ and ‘exclude’

Both parameters are used to specify an array of post IDs to include or exclude respectively.

If you use the ‘include’ parameter, it will only retrieve the posts matching the IDs you specify in the array. Using ‘exclude’ will retrieve the post or posts excluding those in the array.

$args = array(
‘include’ => array(1,2,3),
‘exclude’ => array(6,7,8)
)

‘post_status’

This parameter lets you retrieve posts based on their status. By default, this will retrieve all posts with ‘publish’ status. Other post statuses available include draft, pending, any, future, and trash.

$args = array(‘post_status’ => ‘publish’)

Retrieving WordPress Posts with get_posts Function

Now that we are familiar with the parameters you have available on the get_posts function, we will perform simple queries using some of the parameters to build lists of posts.

Before we start, we recommend testing the code on a staging site or a local installation on your computer. Also, backup your site before pushing the code to your live site.

To use this function, you have to edit a theme template file. You can access your templates by going to Appearance >> Theme Editor in your WP dashboard. In this example, we’ll show you how to retrieve a list of posts and display them on your blog page. In that case, you have to paste the code below in the blog.php template.

Sidenote: If this template does not exist, you may have to create it. See our guide on creating custom templates. Also, if you are creating a new template, then all the code below should be placed in between opening and closing php tags. I.e. <?php all_code_here ?>.

Copy this code and paste it into your blog.php template.

$args = array(
‘numberposts’ => 20,
‘post_type’ => ‘post’,
‘order_by’ => ‘comment_count’,
‘order’ => ‘ASC’,);$posts_list = get_posts($args);

The code above retrieves an array of wp posts. We set the custom parameters to retrieve a list of the first 20 posts.

Additionally, we use the order_by parameter to order the results in ascending order of comment counts. This means the posts with the most comments will be displayed first.

Lastly, we call the get_posts function and store the results in the $posts_list variable.

How to display posts with WordPress get_posts function

In the section above, we used the WordPress getposts function to retrieve a list of post objects.

Now, we will display the results on a page using the PHP foreach loop in WordPress. Copy and paste the code below into the blog.php template, just underneath the code we pasted in the section above.

if( ! empty( $posts_list ) ){
$output = ‘<ul>’;
foreach ( $posts_list as $p ){
$output .= ‘<li><a href=”‘ . get_permalink( $p->ID ) . ‘”>’
. $p->post_title . ‘</a></li>’;
}
$output .= ‘<ul>’;
}echo $output ?? ‘<strong>Sorry. There are no posts for your specified criteria!</strong>’;

After retrieving a list of wp_post objects, we use the foreach cycle to loop through the array of posts and then render a link with the posts permalink and the post title. If you visit your blog page, it should display the list as seen below.

Displaying posts with the WordPress get_posts function

Side note: For this to work, you may have to select the blog.php template as the one used on your blog page.

Select the blog.php template

If this template does not appear on your list of templates, add this code just after the opening php tag at the top of your blog.php template:

/* Template Name: Blog Template */

There are other parameters available on every wp_post object that you can render on your page. Below are some of the commonly used post parameters.

Commonly Used Post Parameters

  • ID: A unique identifier for each post object.
  • post_author: The author of the post identified using the author id parameter.
  • post_date: Date and time which the post was published
  • post_content: The main content or body of the post.
  • post_title: This is the title you set when creating the post
  • post_excerpt: Brief summary of the post.
  • post_status: Specifies whether a post is published, draft, or trash.
  • comment_status: A boolean that returns true if comments are allowed on the page. Otherwise, it returns false.
  • post_modified: This shows the date and time the post was last modified.
  • post_type: Specifies the type of the post object. Options include post, page, and custom post types.
  • comment_count: An integer that shows the total number of comments on a particular post.

You can find other parameters available in the wp_post table in your WordPress database. Simply go to the PHPmyadmin section of your WordPress hosting.

phpmyadmin - WordPress get_post

Display other Post Types with the WordPress get_posts Function

If you want to display a list of pages on your website, simply change the post_type parameter to pages. For this, copy and paste the code below.

$args = array(
‘numberposts’ => 10,
‘post_type’ => ‘page’,
);$page_list = get_posts( $args );if( ! empty( $page_list ) ){
$output = ‘<ul>’;
foreach ( $page_list as $p ){
$output .= ‘<li><a href=”‘ . get_permalink( $p->ID ) . ‘”>’
. $p->post_title . ‘</a></li>’;
}
$output .= ‘<ul>’;
}echo $output ?? ‘<strong>Sorry. There are no posts for your specified criteria!</strong>’;

You can also use this function to build complex queries to display custom lists of posts, and the result set will be customized based on the filters you use.

In the code sample below, we have selected the music post type and filtered the results from a particular genre using the array taxonomy parameter.

 

$args = array(
‘post_type’ => ‘music’,
‘tax_query’ => array(
array(
‘taxonomy’ => ‘music_genre’,
‘field’ => ‘slug’,
‘terms’ => ‘blues’
)
),
);
$custom_post = get_posts( $args );if( ! empty( $custom_post ) ){
$output = ‘<ul>’;
foreach ( $custom_post as $p ){
$output .= ‘<li><a href=”‘ . get_permalink( $p->ID ) . ‘”>’
. $p->post_title . ‘</a></li>’;
}
$output .= ‘<ul>’;
}
echo $output ?? ‘<strong>Sorry. There are no posts for your specified criteria!</strong>’;

Conclusion – WordPress get_posts

The get_posts WordPress function is a powerful tool for creating custom queries and manipulating the wp_post table.

It is a handy tool for WordPress developers intending to create a page or section on a website to display posts based on some parameters.

For instance, if you want to add a widget on your site to display the most popular posts on your website, you can use the get_posts function and use the comment_count keyword to order the result.

This guide has shown you how get_posts works and how to retrieve and display WordPress posts using this function.

 This post was written by Mesheal Fegor

Mesheal Fegor is a Web/WordPress Developer and technical writer. His WordPress help articles have been featured on Kinsta and other sites. Mesheal holds a master's degree in computer science. His writing focuses on technical WordPress issues, ranging from core WordPress problems, to issues with WooCommerce, and more.

Last edited by: FixRunner Team