返回介绍

get_posts()

发布于 2017-09-10 23:48:46 字数 16655 浏览 1108 评论 0 收藏 0

get_posts( array $args = null )

Retrieve list of latest posts or posts matching criteria.


description

The defaults are as follows:


参数

$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'
    (array) 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'
    (array) An array of post IDs not to retrieve. Default empty array.
  • 'suppress_filters'
    (bool) Whether to suppress filters. Default true.

Default value: null


返回值

(array) List of posts.


源代码

File: wp-includes/post.php

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

	$r = wp_parse_args( $args, $defaults );
	if ( empty( $r['post_status'] ) )
		$r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
	if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
		$r['posts_per_page'] = $r['numberposts'];
	if ( ! empty($r['category']) )
		$r['cat'] = $r['category'];
	if ( ! empty($r['include']) ) {
		$incposts = wp_parse_id_list( $r['include'] );
		$r['posts_per_page'] = count($incposts);  // only the number of posts included
		$r['post__in'] = $incposts;
	} elseif ( ! empty($r['exclude']) )
		$r['post__not_in'] = wp_parse_id_list( $r['exclude'] );

	$r['ignore_sticky_posts'] = true;
	$r['no_found_rows'] = true;

	$get_posts = new WP_Query;
	return $get_posts->query($r);

}

更新日志

Versiondescription
1.2.0Introduced.

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.


相关函数

Uses

  • wp-includes/class-wp-query.php: WP_Query::__construct()
  • wp-includes/functions.php: wp_parse_args()
  • wp-includes/functions.php: wp_parse_id_list()

Used By

  • wp-includes/post.php: wp_add_trashed_suffix_to_post_name_for_trashed_posts()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::load_available_items_query()
  • wp-includes/post.php: get_children()
  • wp-admin/includes/image.php: wp_generate_attachment_metadata()
  • wp-admin/includes/dashboard.php: wp_dashboard_recent_drafts()
  • wp-admin/includes/ajax-actions.php: wp_ajax_find_posts()
  • wp-admin/includes/nav-menu.php: wp_nav_menu_item_post_type_meta_box()
  • wp-includes/theme.php: get_uploaded_header_images()
  • wp-includes/class-wp-query.php: WP_Query::get_posts()
  • wp-includes/link-template.php: get_boundary_post()
  • wp-includes/media.php: gallery_shortcode()
  • wp-includes/media.php: wp_playlist_shortcode()
  • wp-includes/post.php: wp_get_recent_posts()
  • wp-includes/nav-menu.php: wp_get_nav_menu_items()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::wp_getMediaLibrary()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::wp_getPages()
  • Show 11 more used by Hide more used by

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 4You must log in to vote on the helpfulness of this note Contributed by Nicola Mustone

    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 );
    
  2. Access all post data

    Some post-相关函数 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; ?>
    

    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.

    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>
    

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

    You can check all the parameters that can be used on get_posts on https://codex.wordpress.org/Class_Reference/WP_Query#Parameters

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

    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>
    

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

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

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

    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.

    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.

    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] =>
    )
    

    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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文