get_posts( array $args = null ): WP_Post[]|int[]

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:

Top ↑

See also


Top ↑

Parameters

$args array Optional
Arguments to retrieve posts. See WP_Query::parse_query() for all available arguments.
  • numberposts int
    Total number of posts to retrieve. Is an alias of $posts_per_page in WP_Query. Accepts -1 for all. Default 5.
  • category int|string
    Category 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 bool
    Whether to suppress filters. Default true.
More Arguments from WP_Query::parse_query( ... $query ) Array or string of Query parameters.
  • attachment_id int
    Attachment post ID. Used for 'attachment' post_type.
  • author int|string
    Author ID, or comma-separated list of IDs.
  • author_name string
    User 'user_nicename'.
  • author__in int[]
    An array of author IDs to query from.
  • author__not_in int[]
    An array of author IDs not to query from.
  • cache_results bool
    Whether to cache post information. Default true.
  • cat int|string
    Category ID or comma-separated list of IDs (this or any children).
  • category__and int[]
    An array of category IDs (AND in).
  • category__in int[]
    An array of category IDs (OR in, no children).
  • category__not_in int[]
    An array of category IDs (NOT in).
  • category_name string
    Use category slug (not name, this or any children).
  • comment_count array|int
    Filter results by comment count. Provide an integer to match comment count exactly. Provide an array with integer 'value' and 'compare' operator ('=', '!=', '>', '>=', '<', '<=' ) to compare against comment_count in a specific way.
  • comment_status string
    Comment status.
  • comments_per_page int
    The number of comments to return per page.
    Default 'comments_per_page' option.
  • date_query array
    An associative array of WP_Date_Query arguments.
    See WP_Date_Query::__construct().
  • day int
    Day of the month. Accepts numbers 1-31.
  • exact bool
    Whether to search by exact keyword. Default false.
  • fields string
    Post fields to query for. Accepts:
    • '' Returns an array of complete post objects (WP_Post[]).
    • 'ids' Returns an array of post IDs (int[]).
    • 'id=>parent' Returns an associative array of parent post IDs, keyed by post ID (int[]).
    Default ''.
  • hour int
    Hour of the day. Accepts numbers 0-23.
  • ignore_sticky_posts int|bool
    Whether to ignore sticky posts or not. Setting this to false excludes stickies from 'post__in'. Accepts 1|true, 0|false.
    Default false.
  • m int
    Combination YearMonth. Accepts any four-digit year and month numbers 01-12.
  • meta_key string|string[]
    Meta key or keys to filter by.
  • meta_value string|string[]
    Meta value or values to filter by.
  • meta_compare string
    MySQL operator used for comparing the meta value.
    See WP_Meta_Query::__construct() for accepted values and default value.
  • meta_compare_key string
    MySQL operator used for comparing the meta key.
    See WP_Meta_Query::__construct() for accepted values and default value.
  • meta_type string
    MySQL data type that the meta_value column will be CAST to for comparisons.
    See WP_Meta_Query::__construct() for accepted values and default value.
  • meta_type_key string
    MySQL data type that the meta_key column will be CAST to for comparisons.
    See WP_Meta_Query::__construct() for accepted values and default value.
  • meta_query array
    An associative array of WP_Meta_Query arguments.
    See WP_Meta_Query::__construct() for accepted values.
  • menu_order int
    The menu order of the posts.
  • minute int
    Minute of the hour. Accepts numbers 0-59.
  • monthnum int
    The two-digit month. Accepts numbers 1-12.
  • name string
    Post slug.
  • nopaging bool
    Show all posts (true) or paginate (false). Default false.
  • no_found_rows bool
    Whether to skip counting the total rows found. Enabling can improve performance. Default false.
  • offset int
    The number of posts to offset before retrieval.
  • order string
    Designates ascending or descending order of posts. Default 'DESC'.
    Accepts 'ASC', 'DESC'.
  • orderby string|array
    Sort retrieved posts by parameter. One or more options may be passed.
    To use 'meta_value', or 'meta_value_num', 'meta_key=keyname' must be also be defined. To sort by a specific $meta_query clause, use that clause's array key. Accepts:
    • 'none'
    • 'name'
    • 'author'
    • 'date'
    • 'title'
    • 'modified'
    • 'menu_order'
    • 'parent'
    • 'ID'
    • 'rand'
    • 'relevance'
    • 'RAND(x)' (where 'x' is an integer seed value)
    • 'comment_count'
    • 'meta_value'
    • 'meta_value_num'
    • 'post__in'
    • 'post_name__in'
    • 'post_parent__in'
    • The array keys of $meta_query.
    Default is 'date', except when a search is being performed, when the default is 'relevance'.
  • p int
    Post ID.
  • page int
    Show the number of posts that would show up on page X of a static front page.
  • paged int
    The number of the current page.
  • page_id int
    Page ID.
  • pagename string
    Page slug.
  • perm string
    Show posts if user has the appropriate capability.
  • ping_status string
    Ping status.
  • post__in int[]
    An array of post IDs to retrieve, sticky posts will be included.
  • post__not_in int[]
    An array of post IDs not to retrieve. Note: a string of comma- separated IDs will NOT work.
  • post_mime_type string
    The mime type of the post. Used for 'attachment' post_type.
  • post_name__in string[]
    An array of post slugs that results must match.
  • post_parent int
    Page ID to retrieve child pages for. Use 0 to only retrieve top-level pages.
  • post_parent__in int[]
    An array containing parent page IDs to query child pages from.
  • post_parent__not_in int[]
    An array containing parent page IDs not to query child pages from.
  • post_type string|string[]
    A post type slug (string) or array of post type slugs.
    Default 'any' if using 'tax_query'.
  • post_status string|string[]
    A post status (string) or array of post statuses.
  • posts_per_page int
    The number of posts to query for. Use -1 to request all posts.
  • posts_per_archive_page int
    The number of posts to query for by archive page. Overrides 'posts_per_page' when is_archive() , or is_search() are true.
  • s string
    Search keyword(s). Prepending a term with a hyphen will exclude posts matching that term. Eg, 'pillow -sofa' will return posts containing 'pillow' but not 'sofa'. The character used for exclusion can be modified using the the 'wp_query_search_exclusion_prefix' filter.
  • second int
    Second of the minute. Accepts numbers 0-59.
  • sentence bool
    Whether to search by phrase. Default false.
  • suppress_filters bool
    Whether to suppress filters. Default false.
  • tag string
    Tag slug. Comma-separated (either), Plus-separated (all).
  • tag__and int[]
    An array of tag IDs (AND in).
  • tag__in int[]
    An array of tag IDs (OR in).
  • tag__not_in int[]
    An array of tag IDs (NOT in).
  • tag_id int
    Tag id or comma-separated list of IDs.
  • tag_slug__and string[]
    An array of tag slugs (AND in).
  • tag_slug__in string[]
    An array of tag slugs (OR in). unless 'ignore_sticky_posts' is true. Note: a string of comma-separated IDs will NOT work.
  • tax_query array
    An associative array of WP_Tax_Query arguments.
    See WP_Tax_Query::__construct().
  • title string
    Post title.
  • update_post_meta_cache bool
    Whether to update the post meta cache. Default true.
  • update_post_term_cache bool
    Whether to update the post term cache. Default true.
  • update_menu_item_cache bool
    Whether to update the menu item cache. Default false.
  • lazy_load_term_meta bool
    Whether to lazy-load term meta. Setting to false will disable cache priming for term meta, so that each get_term_meta() call will hit the database.
    Defaults to the value of $update_post_term_cache.
  • w int
    The week number of the year. Accepts numbers 0-53.
  • year int
    The four-digit year. Accepts any four-digit year.

Default: null


Top ↑

Return

WP_Post[]|int[] Array of post objects or post IDs.


Top ↑

More Information

The most appropriate use for get_posts is to create an array of posts based on a set of parameters. It retrieves a list of recent posts or posts matching this criteria. get_posts can also be used to create Multiple Loops, though a more direct reference to WP_Query using new WP_Query is preferred in this case.

The parameters of get_posts are similar to those of get_pages but are implemented quite differently, and should be used in appropriate scenarios. get_posts uses WP_Query, whereas get_pages queries the database more directly. Each have parameters that reflect this difference in implementation.

query_posts also uses WP_Query, but is not recommended because it directly alters the main loop by changing the variables of the global variable $wp_query. get_posts, on the other hand, simply references a new WP_Query object, and therefore does not affect or alter the main loop.

If you would like to alter the main query before it is executed, you can hook into it using pre_get_posts. If you would just like to call an array of posts based on a small and simple set of parameters within a page, then get_posts is your best option.


Top ↑

Source

File: wp-includes/post.php. View all references

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 );

}


Top ↑

Changelog

Changelog
Version Description
1.2.0 Introduced.

Top ↑

User Contributed Notes

  1. Skip to note 1 content
    Contributed by Aurovrata Venet

    Returns an array of WP_Post objects with attributes,

    WP_Post Object
    (
        [ID] =>
        [post_author] =>
        [post_date] => 
        [post_date_gmt] => 
        [post_content] => 
        [post_title] => 
        [post_excerpt] => 
        [post_status] =>
        [comment_status] =>
        [ping_status] => 
        [post_password] => 
        [post_name] =>
        [to_ping] => 
        [pinged] => 
        [post_modified] => 
        [post_modified_gmt] =>
        [post_content_filtered] => 
        [post_parent] => 
        [guid] => 
        [menu_order] =>
        [post_type] =>
        [post_mime_type] => 
        [comment_count] =>
        [filter] =>
    )
  2. Skip to note 2 content
    Contributed by swedish boy

    Array of post IDs

    To return ids instead of post objects use the fields argument.

    $args = array('fields' => 'ids');
    $posts = get_posts($args);
    // if any posts are found $posts will be an array with their ids

    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

  3. Skip to note 3 content
    Contributed by Nico

    Example to get the latest 10 posts in the blog:

    $args = array(
      'numberposts' => 10
    );
    
    $latest_posts = get_posts( $args );

    You can also pass the post_type argument if you want to get posts from a Custom Post Type, like:

    $args = array(
      'numberposts' => 10,
      'post_type'   => 'book'
    );
    
    $latest_books = get_posts( $args );
  4. Skip to note 4 content
    Contributed by Codex

    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’:

    $args = array(
    	'post_type'  => 'product',
    	'meta_query' => array(
    		array(
    			'key'   => 'featured',
    			'value' => 'yes',
    		)
    	)
    );
    $postslist = get_posts( $args );

    Refer to the custom fields parameters section of the WP_Query documentation for more examples.

  5. Skip to note 5 content
    Contributed by Codex

    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.

    <?php
    $post_list = get_posts( array(
    	'orderby'    => 'menu_order',
    	'sort_order' => 'asc'
    ) );
    
    $posts = array();
    
    foreach ( $post_list as $post ) {
       $posts[] += $post->ID;
    }
    
    $current = array_search( get_the_ID(), $posts );
    
    $prevID = $posts[ $current-1 ];
    $nextID = $posts[ $current+1 ];
    ?>
    
    <div class="navigation">
    <?php if ( ! empty( $prevID ) ): ?>
    	<div class="alignleft">
    		<a href="<?php echo get_permalink( $prevID ); ?>" alt="<?php echo get_the_title( $prevID ); ?>">
    			<?php _e( 'Previous', 'textdomain' ); ?>
    		</a>
    	</div>
    <?php endif;
    
    if ( ! empty( $nextID ) ) : ?>
    	<div class="alignright">
    		<a href="<?php echo get_permalink( $nextID ); ?>" alt="<?php echo get_the_title( $nextID ); ?>">
    			<?php _e( 'Next', 'textdomain' ); ?>
    		</a>
    	</div>
    <?php endif; ?>
    </div><!-- .navigation -->

    Reset after Postlists with offset

    If you need after the loop, the post you had before joining the foreach, you can use this:

    <ul>
    	<?php
    	global $post;
    
    	$myposts = get_posts( array(
    		'posts_per_page' => 5,
    		'offset'         => 1,
    		'category'       => 1
    	) );
    
    	if ( $myposts ) {
    		foreach ( $myposts as $post ) : 
    			setup_postdata( $post ); ?>
    			<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    		<?php
    		endforeach;
    		wp_reset_postdata();
    	}
    	?>
    </ul>
  6. Skip to note 6 content
    Contributed by Codex

    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:

    <?php
    $lastposts = get_posts( array(
    	'posts_per_page' => 3
    ) );
    
    if ( $lastposts ) {
    	foreach ( $lastposts as $post ) :
    		setup_postdata( $post ); ?>
    		<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    		<?php the_content(); ?>
    	<?php
    	endforeach; 
    	wp_reset_postdata();
    }

    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:

    <?php echo $post->ID; ?>
  7. Skip to note 7 content
    Contributed by Codex

    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.

    $show_albums = get_posts( array(
    	 'posts_per_page' => 8,
    	 'orderby'        => 'rand',
    	 'post_type'      => 'albums',
    	 'genre'          => 'jazz',
    	 'post_status'    => 'publish'
    ) );

    Following example displays posts tagged with ‘jazz’, under ‘genre’ custom taxonomy, using ‘tax_query’:

    $args = array(
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'genre',
    			'field'    => 'slug',
    			'terms'    => 'jazz'
    		)
    	)
    );
    $postslist = get_posts( $args );

    Refer to the taxonomy parameters section of the WP_Query documentation for more examples.

  8. Skip to note 9 content
    Contributed by Codex

    Get a post by its slug

    Allows you to get a post ID by post slug.

    <?php
    $the_slug = 'my-slug';
    $args=array(
    	'name'           => $the_slug,
    	'post_type'      => 'post',
    	'post_status'    => 'publish',
    	'posts_per_page' => 1
    );
    $my_posts = get_posts( $args );
    
    if ( $my_posts ) {
    	printf( __( 'ID on the first post found %s', 'textdomain' ), esc_html( $my_posts[0]->ID ) );
    }
  9. Skip to note 10 content
    Contributed by Toao.net

    orderby also accepts the value post__in. (Note two underscores between post and in.) If you used include to retrieve specific posts, the posts will be supplied in the order you supplied to include. For example:

    $posts = get_posts( array(
    	'include'   => '3,8,1,17',
    	'post_type' => 'attachment',
    	'orderby'   => 'post__in',
    ) );
  10. Skip to note 12 content
    Contributed by Codex

    Show all attachments

    Do this outside any Loops in your template.

    <?php
    $attachments = get_posts( array(
    	'post_type'      => 'attachment',
    	'posts_per_page' => 500,
    	'post_status'    => 'any',
    	'post_parent'    => null
    ) );
    
    if ( $attachments ) {
    	foreach ( $attachments as $post ) {
    		setup_postdata( $post );
    		the_title();
    		the_attachment_link( $post->ID, false );
    		the_excerpt();
    	}
    	wp_reset_postdata();
    }
    ?>
  11. Skip to note 14 content

    Example to display posts or post type ‘album’, tagged with ‘jazz’ or ‘improv’ under the ‘genre’ custom taxonomy:

    $args = array(
        'post_type' => 'album',
        'post_status' => 'publish',
        'tax_query' => array(
            array(
                'taxonomy' => 'genre',
                'field'    => 'slug',
                'terms'    => array( 'jazz', 'improv' )
            )
        )
    );
    $postslist = get_posts( $args );

    Note that the simple '{custom_taxonomy_name}' => 'jazz' has been deprecated in favor of tax_query. More complex examples can be found on https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

  12. Skip to note 15 content
    Contributed by Codex

    Latest 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:

    $postslist = get_posts( array(
    	'posts_per_page' => 10,
    	'order'          => 'ASC',
    	'orderby'        => 'title'
    ) );
    
    if ( $postslist ) {
    	foreach ( $postslist as $post ) :
    		setup_postdata( $post );
    		?>
    		<div>
    			<?php the_date(); ?>
    			<br />
    			<?php the_title(); ?>   
    			<?php the_excerpt(); ?>
    		</div>
    	<?php
    	endforeach; 
    	wp_reset_postdata();
    }
  13. Skip to note 16 content
    Contributed by Codex

    Random posts

    Display a list of 5 posts selected randomly by using the MySQL RAND() function for the orderby parameter value:

    <ul>
    	<?php
    	$rand_posts = get_posts( array(
    		'posts_per_page' => 5,
    		'orderby'        => 'rand'
    	) );
    	
    	if ( $rand_posts ) {
    	foreach ( $rand_posts as $post ) : 
    		setup_postdata( $post );
    		?>
    		<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    		<?php
    	endforeach; 
    	wp_reset_postdata();
    	}
    	?>
    </ul>
  14. Skip to note 17 content
    Contributed by Codex

    Show attachments for the current post

    Do this inside The Loop (where $post->ID is available).

    $attachments = get_posts( array(
    	'post_type'      => 'attachment',
    	'posts_per_page' => -1,
    	'post_status'    => 'any',
    	'post_parent'    => $post->ID
    ) );
    
    if ( $attachments ) {
    	foreach ( $attachments as $attachment ) {
    		echo apply_filters( 'the_title' , $attachment->post_title );
    		the_attachment_link( $attachment->ID , false );
    	}
    }
  15. Skip to note 18 content
    Contributed by u22

    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.

    <?php
    		$args = array(
    			'posts_per_page' => 10,
    			'post_type'      => array('page','post'),
    			'post_status'    => 'publish',
    			'offset'	 => 0,
    			's'    		 => 'Lorem',
    			'orderby'        => 'post_type',
            		'order'          => 'ASC'
    		);
    		 $posts = get_posts( $args );
    ?>
  16. Skip to note 20 content
    Contributed by Codex

    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:

    <ul>
    	<?php
    	$myposts = get_posts( $array(
    		'posts_per_page' => 5,
    		'offset'         => 1,
    		'category'       => 1
    	) );
    
    	if ( $myposts ) {
    		foreach ( $myposts as $post ) :
    			setup_postdata( $post );
    			?>
    			<li>
    				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    			</li>
    		<?php
    		endforeach; 
    		wp_reset_postdata();
    	}
    	?>
    </ul>

    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.

You must log in before being able to contribute a note or feedback.