What Is the WordPress get_posts Function and How to Use It to Build PHP Post Lists
The WordPress get_posts function lets you retrieve posts, pages, and custom post types based on given parameters. It works by filtering the posts based on criteria like date, author, type, permission, or meta key.
WordPress site owners can use this function to show relevant content to users quickly. For example, they can display lists of posts with the most comments, the same author, or a similar category.
In this article, we will explain the WordPress get_posts function, including its parameters and objects. You will also learn how to use it to create custom queries for various tasks.
Download all in one WordPress cheat sheet
What Is the WordPress get_posts Function?
The WordPress get_posts function is a feature that lets you query posts based on determined parameters, like the publication date, author, type, permission, or meta key.
WordPress developers use it to quickly find posts matching their given criteria. For example, they can show lists of posts with the most views, the same publication date, or a similar category.
How Does WordPress get_posts Work?
The WordPress get_posts function turns PHP code into SQL queries to fetch post data from your database. These queries are based on your given parameters – the criteria to filter the posts.
To construct the SQL queries, this WordPress function uses the WP_query class. After processing the queries, the database will return an array of WP_post results, each representing an individual post object.
Important! In this case, posts refer to WordPress posts, pages, and custom post types.
WP_query can also pull post content from the WordPress database and display it on the web browser. However, it will alter the WordPress loop, causing issues if you don’t reset it after executing a query.
Meanwhile, the get_posts function automatically resets the loop whenever you run a WordPress query. It lets you send multiple post queries to the WordPress database without issues.
Suggested Reading
Check out our other WordPress tutorials:
How to Export Posts on WordPress
How to Add WordPress Related Posts
How to Schedule Posts in WordPress
WordPress get_posts Function Parameters
The get_posts function has various parameters to apply custom filters. Some of the most used parameters in the WordPress core include:
- Numberposts – sets the number of posts the function will retrieve. The default value is five.
- Category – determines the retrieved posts’ category.
- Include – defines the post IDs you want to include in the query results.
- Exclude – specifies the post IDs you want to exclude from the query results.
- Post_type – filters the post object type your custom query will retrieve. It can be posts, pages, or a custom post type.
- Post_status – affects whether your query will return draft, private, or published posts.
- Order – sorts the retrieved posts in ascending or descending order.
- Orderby – sets the sorting criteria, such as the post date or the number of comments. Use rand to retrieve random posts.
- Post_mime_type – queries attachment post types based on mime type parameters.
- Suppress_filters – determines whether to suppress filters so the query cannot be altered. This parameter defaults to TRUE.
Without custom parameters, the get_posts function will retrieve the latest posts by default. You must attach an array of object posts to the function and specify the arguments for filtering the posts using this syntax:
$example_array = get_posts($arguments); $arguments = array( "parameter_1" => value, "parameter_2" => value );
WP_Posts Objects
The WordPress get_posts function returns an array of post objects containing various information about your website posts. Some of the common properties of the post objects include:
- ID – the post ID number.
- post_author – the post author’s numeric user ID.
- post_title – the post title.
- post_date – the publication date of the post in YYYY-MM-DD format.
- post_content – the content of the post.
- post _status – the current status of the retrieved post, like published or draft.
- post_modified – the post’s last modification date.
- comment_count – the number of comments on the post.
Use foreach to loop the post arrays and echo to display them. Here’s an example of the code structure:
foreach($example_array as $post) { echo "<h1>" . $post->post_title . "</h1><br>"; }
To show the results on any page, add the get_posts function to a child theme template. Alternatively, include it in the blog.php file to show the results on a blog page. On Hostinger’s WordPress plans, these files are accessible via the File Manager.
How to Use the get_posts Function in WordPress
Due to its various parameters, the WordPress get_posts function has diverse use cases. In this section, we will explain the most common ones.
How to Get the Most Popular Posts
Some WordPress sites have widgets showing the most popular posts. To enable it, use get_posts to query an array of post IDs based on the number of comments:
<?php $arguments = array( "orderby" => "comment_count", "posts_per_page" => 10 ); $posts_array = get_posts($arguments); foreach($posts_array as $post) { echo "<h1>" . $post->post_title . "</h1><br>"; echo "<p>" . $post->post_ID . "</p><br>"; } ?>
In the example, we specify arguments that contain an array of parameters that will filter the queried posts. In this case, we use the orderby parameter to sort the posts based on the number of comments.
We also use post_per_page to limit the value of displayed posts per page to 10. Then, we create an array that calls for the get_posts function, which uses $arguments to filter the posts.
After the function retrieves the posts, the foreach method loops the results. Then, the echo function outputs the retrieved post ID and heading.
How to Get Posts by Author
If your WordPress website has multiple contributors, manually finding posts from a specific author can be time-consuming. To quickly do so, use the author parameter to filter the posts:
<?php $arguments = array( "numberposts" => -1, "author" => 2 ); $sample_array = get_posts($arguments); foreach($sample_array as $post) { echo "<h3> " . $post->post_title . "</h3>"; echo "<p>" . $post->post_date . "</p>"; } ?>
In the arguments, we use two parameters – numberposts and author. The numberposts parameter will limit the number of posts shown. Since we set it to -1, all posts will be retrieved.
Meanwhile, the author parameter will filter the posts and only show those from a specific author based on their ID – in this case, the example author’s ID is 2. To query multiple authors, specify the IDs in a comma-separated list.
How to Get Posts in the Same Category
The WordPress get_posts function is commonly used to retrieve posts based on their categories. There are different parameters for this task, most commonly:
- category – based on the category ID.
- category_name – using the category slug, like news or sponsored.
- category__and – querying an array of multiple category IDs.
- category_not_in – getting posts from an excluded category ID.
Regardless of the parameter, the syntax is the same. Here’s an example of a code snippet for querying posts from a category with the ID of 1:
<?php $arguments = array( "numberposts" => -1, "category" => 1, "orderby" => "date", "order" => "DESC" ); $category_array = get_posts($arguments); foreach($sample_array as $post) { echo "<h3> " . $post->post_title . "</h3>"; echo "<p>" . $post->post_ID . "</p>"; } ?>
In the example, we set the number of posts to -1 to show all of them and specify the category ID as the filter. We also use the orderby and order parameters to sort the queried posts in descending order based on their date.
The get_posts function will return posts into $category_array based on the $arguments parameters. Then, the code loops the results to display the queried post ID and title.
If you want to retrieve posts with multiple categories, replace the category parameter with category__and. Then, use a comma-separated list of category IDs as the value. For example, here’s a code that will show posts with 1, 2, and 3 categories:
"category__and" => array("1","2","3")
The category and category_name parameters can also take an array as their value. Unlike category__and, they will retrieve posts from any of the specified categories. Consider the following example:
"category_name" => array("news","archive","sponsored")
The code example will show all posts that belong to one or more of the specified categories. If you use category__and, the function only shows posts from all three categories.
How to Get Posts With Matching Meta Keys and Value
If your WordPress posts have a custom field, you can use get_posts to retrieve them based on a matching meta key and value. Here are the important parameters and their functions:
- meta_key – fetching posts based on the custom field key.
- meta_value – querying posts based on the meta key’s string value.
- meta_value_num – filtering posts similar to meta_value but uses a numerical value.
- meta_compare – applying an operation to test the meta value parameter.
Users can use these parameters together to retrieve posts with a specific meta key and value. Consider the following example:
<?php $arguments = array( "numberposts" => -1, "meta_key" => "color", "meta_value" => "blue", "orderby" => "date", "order" => "ASC" ); $category_array = get_posts($arguments); foreach($sample_array as $post) { echo "<h3> " . $post->post_title . "</h3>"; echo "<p>" . $post->post_date . "</p>"; } ?>
The code queries all posts that have the color custom field with a blue value. If you omit the meta_key parameter, it will retrieve all posts with a blue value, regardless of their custom field name. Conversely, removing meta_value will display posts with the color custom field with any value.
Meanwhile, meta_compare lets you specify an operation to modify how the meta key and value operate. Consider the following code snippet:
<?php $arguments = array( "numberposts" => -1, "meta_key" => "color", "meta_value" => "blue", "meta_compare" => "!=", ); ?>
We use the != value to exclude posts with the specified meta key value. So, it will show an array of posts excluding ones with the blue meta value. We recommend referring to the WordPress documentation for the full operation values.
You may also use multiple meta key-and-value pairs to create a more specific query. To do so, use the meta_query parameter with the filter arrays as its value. Then, use the relation function with the AND or OR value to establish relationships between the arrays. Here’s the syntax:
<?php $arguments = array( "post_type" => "postname", "meta_query" => array( "relation" => "relation", array( "key" => "keyname", "value" => "keyvalue", "compare" => "operation", ), array( "key" => "keyname", "value" => "keyvalue", "compare" => "operation", ), ), ); ?>
How to Get Custom Post Type With Custom Taxonomy
WordPress taxonomy is a mechanism that lets you group content based on its relationships or characteristics. The default taxonomies for WordPress posts are category and tag, but you can add as many new ones as you need.
If your WordPress site has a custom post type, taxonomy helps categorize its content more specifically. For example, a movie post type may have custom taxonomies such as genre and release date.
Querying posts from the same taxonomy uses a similar function to category. Use the custom taxonomy name as the parameter and specify the term name or identifier as the value. For example, the code snippet below will query a custom post type named movie for posts with the review genre:
<?php $arguments = array( "numberposts" => -1, "post_type" => "movie", "genre" => "review", "orderby" => "date", "order" => "ASC" ); $category_array = get_posts($arguments); foreach($sample_array as $post) { echo "<h3> " . $post->post_title . "</h3>"; echo "<p>" . $post->post_date . "</p>"; } ?>
You can also use more than one parameter to create a complex post query using tax_query. It takes an array of arrays as the value, with each containing the following parameters:
- taxonomy – the taxonomy name.
- field – the method for selecting the taxonomy term, whether using an ID, slug, or name. It uses the ID by default.
- terms – the taxonomy term based on the field. To filter multiple taxonomies, use an array as the value.
- include_children – the rule defining whether to include the taxonomy child. It is set to TRUE by default.
- operator – the logical operation for the parameters. Values include IN, NOT IN, AND, EXISTS, and NOT EXISTS.
For example, the following code will query posts with the John tag from the People taxonomy:
<?php $arguments = array( "numberposts" => -1, "tax_query" => array( array( "taxonomy" => "people", "field" => "slug", "terms" => "john", ), ), "orderby" => "date", "order" => "ASC" ); ?>
To use multiple taxonomy queries, add another array into the tax_query parameter. Also, specify the relation between the arrays using the relation parameters with AND or OR values. Here’s an array example:
<?php $arguments = array( "tax_query" => array( "relation" => "AND", array( "taxonomy" => "movie_genre", "field" => "slug", "terms" => array( "thriller", "fantasy" ), ), array( "taxonomy" => "actor", "field" => "term_id", "terms" => array( 90, 105, 207 ), "operator" => "NOT IN", ), ), ?>
Suggested Reading
Learn more about WordPress PHP functions:
How to Use WordPress add_filter
How to Use WordPress wp_update_post
How to Use WordPress get_post_meta Function
Conclusion
The WordPress get_posts function is a method to retrieve an array of posts, pages, or custom post types from the database based on specific query parameters. It is used to quickly display posts matching your given criteria, like comment count or meta keys.
This function uses the WP_query class to construct an SQL query and send it to the WordPress database. The database then returns an array of post objects representing the website posts.
There are various parameters of get_posts, such as numberposts, category, and post_type. It also returns WP_posts objects containing post data like ID, post_author, and post_title.
Developers use the WordPress get_posts function for various tasks and scenarios. Commonly, you can utilize it to retrieve posts with the most comments, the same author, similar categories, and custom taxonomies.
WordPress get_posts FAQ
To help you understand more about the WordPress get_posts function, we will answer several commonly asked questions about it.
What’s the Difference Between get_posts and WP_query?
Both are methods for querying and displaying posts from your website’s database. However, the WP_query class alters the WordPress loop after each query, potentially causing errors if used improperly.
Meanwhile, the get_posts method automatically resets the loop after displaying the requested posts, making it less prone to errors and more convenient.
What Is the Difference Between the get_posts and get_pages Functions?
Unlike get_posts, the get_pages function doesn’t use the WP_query class and queries the database directly. These WordPress functions also have different parameters and retrieved information.For example, get_pages doesn’t use the meta value and key parameters. It also only queries pages and hierarchical post types.
Comments
February 29 2024
How do you get the next page (eg. page 2) of a query if for example there are 100 posts and you have specified "posts_per_page" => 10?
April 18 2024
Hi Denver! When it comes to pagination, it's often more reliable to utilize WP_Query and the WordPress loop instead of relying solely on get_posts(). While adding the paged argument is an option, there can be instances where it doesn't paginate as expected, leading to issues like broken pagination or encountering a 404 error 🕵️