Retrieves an array of the latest posts, or posts matching the given criteria.
Description
For more information on the accepted arguments, see the WP_Query documentation in the Developer Handbook.
The $ignore_sticky_posts
and $no_found_rows
arguments are ignored by this function and both are set to true
.
The defaults are as follows:
See also
Parameters
$args
arrayoptional- Arguments to retrieve posts. See WP_Query::parse_query() for all available arguments.
numberposts
intTotal number of posts to retrieve. Is an alias of$posts_per_page
in WP_Query. Accepts -1 for all. Default 5.category
int|stringCategory ID or comma-separated list of IDs (this or any children).
Is an alias of$cat
in WP_Query. Default 0.include
int[]An array of post IDs to retrieve, sticky posts will be included.
Is an alias of$post__in
in WP_Query. Default empty array.exclude
int[]An array of post IDs not to retrieve. Default empty array.suppress_filters
boolWhether to suppress filters. Default true.
Default:
null
Source
function get_posts( $args = null ) {
$defaults = array(
'numberposts' => 5,
'category' => 0,
'orderby' => 'date',
'order' => 'DESC',
'include' => array(),
'exclude' => array(),
'meta_key' => '',
'meta_value' => '',
'post_type' => 'post',
'suppress_filters' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
if ( empty( $parsed_args['post_status'] ) ) {
$parsed_args['post_status'] = ( 'attachment' === $parsed_args['post_type'] ) ? 'inherit' : 'publish';
}
if ( ! empty( $parsed_args['numberposts'] ) && empty( $parsed_args['posts_per_page'] ) ) {
$parsed_args['posts_per_page'] = $parsed_args['numberposts'];
}
if ( ! empty( $parsed_args['category'] ) ) {
$parsed_args['cat'] = $parsed_args['category'];
}
if ( ! empty( $parsed_args['include'] ) ) {
$incposts = wp_parse_id_list( $parsed_args['include'] );
$parsed_args['posts_per_page'] = count( $incposts ); // Only the number of posts included.
$parsed_args['post__in'] = $incposts;
} elseif ( ! empty( $parsed_args['exclude'] ) ) {
$parsed_args['post__not_in'] = wp_parse_id_list( $parsed_args['exclude'] );
}
$parsed_args['ignore_sticky_posts'] = true;
$parsed_args['no_found_rows'] = true;
$get_posts = new WP_Query();
return $get_posts->query( $parsed_args );
}
Changelog
Version | Description |
---|---|
1.2.0 | Introduced. |
Returns an array of WP_Post objects with attributes,
Array of post IDs
To return ids instead of post objects use the
fields
argument.The
fields
argument can be set to'ids'
,'all'
(default) or'id=>parent'
. The last two (arguments) will return an array of stdClass objects.Source:
https://developer.wordpress.org/reference/classes/wp_query/#return-fields-parameter
Example to get the latest 10 posts in the blog:
You can also pass the
post_type
argument if you want to get posts from a Custom Post Type, like:Custom Field Parameters
Show posts associated with a certain custom field. Following example displays posts from the ‘product’ post type that have meta key ‘featured’ with value ‘yes’, using ‘meta_query’:
Refer to the custom fields parameters section of the WP_Query documentation for more examples.
Posts with Previous Next Navigation
You can also using the custom queries to make the post with Previous and Next Post Navigation. Here is the following method to make it workable.
Reset after Postlists with offset
If you need after the loop, the post you had before joining the foreach, you can use this:
Access all post data
Some post-related data is not available to get_posts by default, such as post content through the_content() , or the numeric ID. This is resolved by calling an internal function setup_postdata() , with the $post array as its argument:
To access a post’s ID or content without calling setup_postdata() , or in fact any post-specific data (data retained in the posts table), you can use $post->COLUMN, where COLUMN is the table column name for the data. So $post->ID holds the ID, $post->post_content the content, and so on. To display or print this data on your page use the PHP echo command, like so:
Taxonomy Parameters
Show posts associated with certain taxonomy. If specifying a taxonomy registered to a custom post type then instead of using ‘category’ you would use ‘{custom_taxonomy_name}’. For instance, if you had a custom taxonomy called “genre” and wanted to only show posts from the “jazz” genre you would use the below code.
Following example displays posts tagged with ‘jazz’, under ‘genre’ custom taxonomy, using ‘tax_query’:
Refer to the taxonomy parameters section of the WP_Query documentation for more examples.
Get all published posts of ANY post type:
Get a post by its slug
Allows you to get a post ID by post slug.
orderby
also accepts the valuepost__in
. (Note two underscores between post and in.) If you usedinclude
to retrieve specific posts, the posts will be supplied in the order you supplied to include. For example:You can check all the parameters that can be used on
get_posts
on https://codex.wordpress.org/Class_Reference/WP_Query#ParametersShow all attachments
Do this outside any Loops in your template.
It is not considered an error condition if no posts are found based on the specified and default parameter values. Instead, an empty array (“
array()
“) is returned by the function.Example to display posts or post type ‘album’, tagged with ‘jazz’ or ‘improv’ under the ‘genre’ custom taxonomy:
Note that the simple
'{custom_taxonomy_name}' => 'jazz'
has been deprecated in favor oftax_query
. More complex examples can be found on https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_ParametersLatest posts ordered by title
To show the last ten posts sorted alphabetically in ascending order, the following will display their post date, title and excerpt:
Random posts
Display a list of 5 posts selected randomly by using the MySQL RAND() function for the orderby parameter value:
Show attachments for the current post
Do this inside The Loop (where $post->ID is available).
Order results by post types names
If you have an array of custom post types you can also order the results by post_type name, this works if you need to “group” the results.
To Find Post By Title
To find a post by its title the array key is ‘title’, NOT ‘post_title’:
Only Published Posts Will Be Found Unless Status Specified
If you are searching for a post that is in draft, private, etc status and not in publish status, get_posts will not find your post unless you include the post_status in the array.
If you use
any
as thepost_status
, it will return all post_status except fortrash
andauto-draft
.Posts list with offset
If you have your blog configured to show just one post on the front page, but also want to list links to the previous five posts in category ID 1, you can use this:
Note: With use of the offset, the above query should be used only on a category that has more than one post in it, otherwise there’ll be no output.