函数文档

get_posts()

💡 云策文档标注

概述

get_posts() 是 WordPress 中用于检索最新文章或符合指定条件文章的数组的函数。它基于 WP_Query 实现,但不会影响主循环,适合在页面中基于简单参数获取文章列表。

关键要点

  • 返回 WP_Post 对象或文章 ID 的数组,默认参数包括 numberposts(默认 5)、category、orderby(默认 'date')、order(默认 'DESC')等。
  • 内部使用 WP_Query,但忽略 sticky posts 和 no_found_rows 参数(均设置为 true),且默认 suppress_filters 为 true。
  • 参数与 WP_Query 兼容,如 numberposts 是 posts_per_page 的别名,category 是 cat 的别名,include 是 post__in 的别名。
  • 适用于创建基于参数的文章数组,如多循环场景,但更推荐直接使用 new WP_Query 进行复杂查询。
  • 与 query_posts 不同,get_posts 不修改主循环;与 get_pages 相比,实现方式不同,应根据场景选择使用。
  • 可通过 pre_get_posts Hook 修改主查询,而 get_posts 适合简单参数调用。

代码示例

// 获取最新 10 篇文章
$args = array(
  'numberposts' => 10
);
$latest_posts = get_posts( $args );

// 获取自定义文章类型 'book' 的最新文章
$args = array(
  'numberposts' => 10,
  'post_type'   => 'book'
);
$latest_books = get_posts( $args );

// 使用 meta_query 查询自定义字段
$args = array(
  'post_type'  => 'product',
  'meta_query' => array(
    array(
      'key'   => 'featured',
      'value' => 'yes',
    )
  )
);
$postslist = get_posts( $args );

// 使用 tax_query 查询分类法
$args = array(
  'tax_query' => array(
    array(
      'taxonomy' => 'genre',
      'field'    => 'slug',
      'terms'    => 'jazz'
    )
  )
);
$postslist = get_posts( $args );

// 返回文章 ID 而非对象
$args = array('fields' => 'ids');
$posts = get_posts($args);

注意事项

  • 默认仅返回发布状态的文章,除非指定 post_status;使用 'any' 可返回除 trash 和 auto-draft 外的所有状态。
  • 未找到文章时返回空数组,而非错误。
  • 使用 setup_postdata() 可访问文章内容等数据,否则需直接通过 $post->COLUMN(如 $post->ID)获取。
  • 参数详情参考 WP_Query 文档,避免使用已弃用的简单分类法参数。

📄 原文内容

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

$argsarrayoptional
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.
  • exclude int[]
    An array of post IDs not to retrieve.
  • suppress_filters bool
    Whether to suppress filters. Default true.

Default:null

Return

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

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.

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.

User Contributed Notes

  1. Skip to note 23 content

    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 24 content

    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 25 content

    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 26 content

    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 27 content

    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.

     '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">
    
    	<div class="alignleft">
    		<a href="<?php echo get_permalink( $prevID ); ?>" alt="<?php echo get_the_title( $prevID ); ?>">
    			
    		</a>
    	</div>
    
    	<div class="alignright">
    		<a href="<?php echo get_permalink( $nextID ); ?>" alt="<?php echo get_the_title( $nextID ); ?>">
    			
    		</a>
    	</div>
    
    </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>
    	 5,
    		'offset'         => 1,
    		'category'       => 1
    	) );
    
    	if ( $myposts ) {
    		foreach ( $myposts as $post ) : 
    			setup_postdata( $post ); ?>
    			<li><a href="<?php the_permalink(); ?>"></a></li>
    		
    </ul>

  6. Skip to note 28 content

    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:

     3
    ) );
    
    if ( $lastposts ) {
    	foreach ( $lastposts as $post ) :
    		setup_postdata( $post ); ?>
    		<h2><a href="<?php the_permalink(); ?>"></a></h2>
    		
    	</pre>
    <p>To access a post’s ID or content without calling <a href="https://developer.wordpress.org/reference/functions/setup_postdata/" rel="function">setup_postdata()</a> , 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:</p>
    <pre class="wp-block-code"><code lang="php" class="language-php ">ID; ?>

  7. Skip to note 29 content

    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 31 content

    Get a post by its slug

    Allows you to get a post ID by post slug.

     $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 32 content

    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 34 content

    Show all attachments

    Do this outside any Loops in your template.

     '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 36 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 38 content

    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>
    			
    			<br />
    			   
    			
    		</div>
    	</pre>
    				</div><!-- .comment-content -->
    
    					<section id='feedback-1190' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='0'>
    </section><!-- .feedback -->
    <footer class='feedback-links wporg-dot-link-list' >
    <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_posts%2F%3Freplytocom%3D1190%23feedback-editor-1190" rel="nofollow">Log in to add feedback</a></footer>
    </article><!-- .comment-body -->
    </li>
    			<li id="comment-1191" data-comment-id="1191" class="comment byuser comment-author-codex even thread-even depth-1">
    			<article id="div-comment-1191" class="comment-body">
    
    							<a href="#comment-content-1191" class="screen-reader-text">Skip to note 39 content</a>
    				<header class="comment-meta">
    					<div class="comment-author vcard">
    						<span class="comment-author-attribution">
    						<a href="https://profiles.wordpress.org/codex/" rel="external nofollow" class="url">Codex</a>						</span>
    						<a class="comment-date" href="https://developer.wordpress.org/reference/functions/get_posts/#comment-1191">
    							<time datetime="2016-02-16T09:12:22+00:00">
    							10 years ago							</time>
    						</a>
    
    																													</div>
    					<div class="user-note-voting" data-nonce="e3364abb22" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="1191" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_posts%2F%23comment-1191"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title=""><span class="screen-reader-text">Vote results for this note: </span>0</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="1191" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_posts%2F%23comment-1191"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div>				</header>
    				<!-- .comment-metadata -->
    			
    				<div class="wporg-has-embedded-code comment-content" id="comment-content-1191">
    				<p><strong>Random posts</strong></p>
    <p>Display a list of 5 posts selected randomly by using the MySQL RAND() function for the orderby parameter value:</p>
    <pre class="wp-block-code"><code lang="php" class="language-php line-numbers"><ul>
    	 5,
    		'orderby'        => 'rand'
    	) );
    	
    	if ( $rand_posts ) {
    	foreach ( $rand_posts as $post ) : 
    		setup_postdata( $post );
    		?>
    		<li><a href="<?php the_permalink(); ?>"></a></li>
    		
    </ul>

  13. Skip to note 40 content

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

  14. Skip to note 41 content

    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.

     10,
    			'post_type'      => array('page','post'),
    			'post_status'    => 'publish',
    			'offset'	 => 0,
    			's'    		 => 'Lorem',
    			'orderby'        => 'post_type',
            		'order'          => 'ASC'
    		);
    		 $posts = get_posts( $args );
    ?>

  15. Skip to note 42 content

    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.

    $post_array = get_posts( array(
    	'post_status' => get_post_stasuses(),
    	'title'       => 'my_post_title'
    ) );

  16. Skip to note 44 content

    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>
    	 5,
    		'offset'         => 1,
    		'category'       => 1
    	) );
    
    	if ( $myposts ) {
    		foreach ( $myposts as $post ) :
    			setup_postdata( $post );
    			?>
    			<li>
    				<a href="<?php the_permalink(); ?>"></a>
    			</li>
    		
    </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.