Table of Contents
Key Takeaways
What is the get_posts() Function?
Why Not Use the WP_Query Object Directly?
What Is the Difference Between get_posts() and get_pages() Functions?
get_posts() Function Parameters
The WP_Post Object
Examples of get_posts
Most Popular Posts
Random Posts
Posts with Matching Meta Key and Value
Custom Post Type with Custom Taxonomy
Conclusion
Frequently Asked Questions (FAQs) about WordPress get_posts Function
What is the difference between get_posts and WP_Query in WordPress?
How can I modify the number of posts returned by get_posts?
Can I use get_posts to retrieve custom post types?
How can I sort the posts returned by get_posts?
Can I use get_posts to retrieve posts from a specific category?
How can I retrieve posts from multiple categories using get_posts?
Can I use get_posts to retrieve posts by a specific author?
How can I retrieve posts that contain a specific meta value using get_posts?
Can I use get_posts to retrieve posts that have a specific tag?
How can I retrieve posts from a specific date range using get_posts?
Home CMS Tutorial WordPress Exploring the WordPress get_posts Function

Exploring the WordPress get_posts Function

Feb 17, 2025 am 10:17 AM

Exploring the WordPress get_posts Function

Key Takeaways

  • The get_posts() function in WordPress is used to retrieve posts from the database by applying custom filters and sorting the final result based on a set of parameters. It returns an array of WP_Post objects, each representing an individual post.
  • The get_posts() function is preferred over the WP_Query object because the latter alters the main loop, potentially causing site issues. The get_posts() function and get_pages() function both retrieve posts, but differ in parameter names, values, and methods of retrieval.
  • The get_posts() function accepts an array of parameters to apply custom filters and sort results. These parameters include posts_per_page, paged, tax_query, orderby, order, exclude, meta_key, meta_value, post_type, and post_status.
  • The get_posts() function can be used to retrieve the most popular posts, random posts, posts with matching meta key and value, and posts of a custom post type with a custom taxonomy name. The returned results are then looped through for further use.

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.

Exploring the WordPress get_posts Function

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:

<span><span><?php 
</span></span><span>
</span><span><span>$args = array(
</span></span><span>	<span>"posts_per_page"   => 5,
</span></span><span>	<span>"paged"            => 1
</span></span><span>	<span>"tax_query" => array(
</span></span><span>		<span>array(
</span></span><span>			<span>"taxonomy" => "category",
</span></span><span>			<span>"field"    => "slug",
</span></span><span>			<span>"terms"    => "videos,movies",
</span></span><span>		<span>)
</span></span><span>	<span>),
</span></span><span>	<span>"orderby"          => "post_date",
</span></span><span>	<span>"order"            => "DESC",
</span></span><span>	<span>"exclude"          => "1123, 4456",
</span></span><span>	<span>"meta_key"         => "",
</span></span><span>	<span>"meta_value"       => "",
</span></span><span>	<span>"post_type"        => "post",
</span></span><span>	<span>"post_status"      => "publish"
</span></span><span><span>);
</span></span><span>
</span><span><span>$posts_array = get_posts($args); 
</span></span><span>
</span><span><span>?></span></span>
Copy after login
Copy after login

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:

<span><span><?php 
</span></span><span>
</span><span><span>$args = array(
</span></span><span>	<span>"posts_per_page"   => 5,
</span></span><span>	<span>"paged"            => 1
</span></span><span>	<span>"tax_query" => array(
</span></span><span>		<span>array(
</span></span><span>			<span>"taxonomy" => "category",
</span></span><span>			<span>"field"    => "slug",
</span></span><span>			<span>"terms"    => "videos,movies",
</span></span><span>		<span>)
</span></span><span>	<span>),
</span></span><span>	<span>"orderby"          => "post_date",
</span></span><span>	<span>"order"            => "DESC",
</span></span><span>	<span>"exclude"          => "1123, 4456",
</span></span><span>	<span>"meta_key"         => "",
</span></span><span>	<span>"meta_value"       => "",
</span></span><span>	<span>"post_type"        => "post",
</span></span><span>	<span>"post_status"      => "publish"
</span></span><span><span>);
</span></span><span>
</span><span><span>$posts_array = get_posts($args); 
</span></span><span>
</span><span><span>?></span></span>
Copy after login
Copy after login

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:

<span><span><?php
</span></span><span>	<span>$args = array("posts_per_page" => 10, "orderby" => "comment_count");
</span></span><span>	<span>$posts_array = get_posts($args);
</span></span><span>	<span>foreach($posts_array as $post)
</span></span><span>	<span>{
</span></span><span>	  <span>echo "<h1>" . $post->post_title . "</h1><br>";
</span></span><span>	  <span>echo "<p>" . $post->post_content . "</p><br>";
</span></span><span>	<span>} 
</span></span><span><span>?></span></span>
Copy after login

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:

<span><span><?php
</span></span><span>  <span>$args = array("posts_per_page" => 1, "orderby" => "rand");
</span></span><span>  <span>$posts_array = get_posts($args);
</span></span><span>  <span>foreach($posts_array as $post)
</span></span><span>  <span>{
</span></span><span>    <span>echo "<h1>" . $post->post_title . "</h1><br>";
</span></span><span>    <span>echo "<p>" . $post->post_content . "</p><br>";
</span></span><span>  <span>} 
</span></span><span><span>?></span></span>
Copy after login

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:

<span><span><?php
</span></span><span>  <span>$args = array("posts_per_page" => -1, "meta_key" => "reviewer", "meta_value" = "narayanprusty");
</span></span><span>  <span>$posts_array = get_posts($args);
</span></span><span>  <span>foreach($posts_array as $post)
</span></span><span>  <span>{
</span></span><span>    <span>echo "<h1>" . $post->post_title . "</h1><br>";
</span></span><span>    <span>echo "<p>" . $post->post_content . "</p><br>";
</span></span><span>  <span>} 
</span></span><span><span>?></span></span>
Copy after login

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.

Frequently Asked Questions (FAQs) about WordPress get_posts Function

What is the difference between get_posts and WP_Query in WordPress?

Both get_posts and WP_Query are used to retrieve posts from your WordPress database. However, they differ in their usage and flexibility. get_posts is a simpler function, ideal for beginners and for situations where you only need to retrieve a specific set of posts. On the other hand, WP_Query is more powerful and flexible. It allows for more complex queries and gives you more control over the WordPress loop. While get_posts is easier to use, WP_Query provides more advanced features for customizing your queries.

How can I modify the number of posts returned by get_posts?

You can control the number of posts returned by get_posts by using the ‘numberposts’ parameter. By default, it is set to 5. If you want to retrieve all posts, you can set ‘numberposts’ to -1. For example, to get 10 posts, you would use: get_posts(array(‘numberposts’ => 10));

Can I use get_posts to retrieve custom post types?

Yes, you can use get_posts to retrieve custom post types. You just need to specify the ‘post_type’ parameter in your query. For example, if you have a custom post type called ‘products’, you can retrieve these posts with: get_posts(array(‘post_type’ => ‘products’));

How can I sort the posts returned by get_posts?

You can sort the posts returned by get_posts by using the ‘orderby’ and ‘order’ parameters. ‘orderby’ determines the field to sort by, and ‘order’ determines the sorting order (ASC for ascending and DESC for descending). For example, to sort posts by title in ascending order, you would use: get_posts(array(‘orderby’ => ‘title’, ‘order’ => ‘ASC’));

Can I use get_posts to retrieve posts from a specific category?

Yes, you can use get_posts to retrieve posts from a specific category. You just need to specify the ‘category’ parameter in your query. For example, to get posts from the category with the ID 3, you would use: get_posts(array(‘category’ => 3));

How can I retrieve posts from multiple categories using get_posts?

To retrieve posts from multiple categories, you can pass an array of category IDs to the ‘category’ parameter. For example, to get posts from the categories with the IDs 3 and 4, you would use: get_posts(array(‘category’ => array(3, 4)));

Can I use get_posts to retrieve posts by a specific author?

Yes, you can use get_posts to retrieve posts by a specific author. You just need to specify the ‘author’ parameter in your query. For example, to get posts by the author with the ID 1, you would use: get_posts(array(‘author’ => 1));

How can I retrieve posts that contain a specific meta value using get_posts?

To retrieve posts that contain a specific meta value, you can use the ‘meta_key’ and ‘meta_value’ parameters. For example, to get posts that have a meta key of ‘color’ and a meta value of ‘blue’, you would use: get_posts(array(‘meta_key’ => ‘color’, ‘meta_value’ => ‘blue’));

Can I use get_posts to retrieve posts that have a specific tag?

Yes, you can use get_posts to retrieve posts that have a specific tag. You just need to specify the ‘tag’ parameter in your query. For example, to get posts that have the tag ‘WordPress’, you would use: get_posts(array(‘tag’ => ‘WordPress’));

How can I retrieve posts from a specific date range using get_posts?

To retrieve posts from a specific date range, you can use the ‘date_query’ parameter. This parameter accepts an array of arrays, with each inner array defining a date query clause. For example, to get posts from January 2020, you would use: get_posts(array(‘date_query’ => array(array(‘year’ => 2020, ‘month’ => 1))));

The above is the detailed content of Exploring the WordPress get_posts Function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to Automate WordPress and Social Media with IFTTT (and more) How to Automate WordPress and Social Media with IFTTT (and more) Apr 18, 2025 am 11:27 AM

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

See all articles