WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Template Tags/get posts

Description

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.

Usage

 <?php $posts_array get_posts$args ); ?> 

Default Usage

<?php $args = array(
	'posts_per_page'   => 5,
	'offset'           => 0,
	'category'         => '',
	'category_name'    => '',
	'orderby'          => 'post_date',
	'order'            => 'DESC',
	'include'          => '',
	'exclude'          => '',
	'meta_key'         => '',
	'meta_value'       => '',
	'post_type'        => 'post',
	'post_mime_type'   => '',
	'post_parent'      => '',
	'post_status'      => 'publish',
	'suppress_filters' => true ); ?>

Note: 'numberposts' and 'posts_per_page' can be used interchangeably.

Parameters

For full parameters list see WP_Query.

See also get_pages() for example parameter usage.

get_posts() makes use of the WP_Query class to fetch posts. See the parameters section of the WP_Query documentation for a list of parameters that this function accepts.

Note: get_posts uses 'suppress_filters' => true as default, while query_posts() applies filters by default, this can be confusing when using query-modifying plugins, like WPML. Also note that even if 'suppress_filters' is true, any filters attached to pre_get_posts are still applied—only filters attached on 'posts_*' or 'comment_feed_*' are suppressed.

Note: The category parameter needs to be the ID of the category, and not the category name.

Note: The category parameter can be a comma separated list of categories, as the get_posts() function passes the 'category' parameter directly into WP_Query as 'cat'.

Note: The category_name parameter needs to be a string, in this case, the category name.

'orderby'
(string) (optional) Sort retrieved posts by parameter.
Default: 'date'
  • 'none' - No order (available with Version 2.8).
  • 'ID' - Order by post id. Note the capitalization.
  • 'author' - Order by author.
  • 'title' - Order by title.
  • 'date' - Order by date.
  • 'modified' - Order by last modified date.
  • 'parent' - Order by post/page parent id.
  • 'rand' - Random order.
  • 'comment_count' - Order by number of comments (available with Version 2.9).
  • 'menu_order' - Order by Page Order. Used most often for Pages (Order field in the Edit Page Attributes box) and for Attachments (the integer fields in the Insert / Upload Media Gallery dialog), but could be used for any post type with distinct 'menu_order' values (they all default to 0).
  • 'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note also that the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect).
  • 'meta_value_num' - Order by numeric meta value (available with Version 2.8). Also note that a 'meta_key=keyname' must also be present in the query. This value allows for numerical sorting as noted above in 'meta_value'.
  • 'post__in' - Matches same order you passed in via the 'include' parameter.
Note: get_pages() uses the parameter 'sort_column' instead of 'orderby'. Also, get_pages() requires that 'post_' be prepended to these values: 'author, date, modified, parent, title, excerpt, content'.
'post_mime_type'
(string or array) (Optional) List of mime types or comma separated string of mime types.
Default: None

Return Value

(array) 
List of WP_Post objects.

Unlike get_pages(), get_posts() will return private pages in the appropriate context (i.e., for an administrator). (See: Andreas Kirsch, WordPress Hacking II, January 24, 2009-- accessed 2012-11-09.)

Examples

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


$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );

$myposts = get_posts( $args );
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.

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
$postlist = get_posts( 'sort_column=menu_order&sort_order=asc' );
$posts = array();
foreach ( $postlist 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 ); ?>"
  title="<?php echo get_the_title( $prevID ); ?>">Previous</a>
</div>
<?php endif;
if ( !empty( $nextID ) ): ?>
<div class="alignright">
<a href="<?php echo get_permalink( $nextID ); ?>" 
 title="<?php echo get_the_title( $nextID ); ?>">Next</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;
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : 
  setup_postdata( $post ); ?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach;
wp_reset_postdata(); ?>
</ul>

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
$args = array( 'posts_per_page' => 3 );
$lastposts = get_posts( $args );
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; ?>

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:

<?php
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
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
$args = array( 'posts_per_page' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
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
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => null ); 
$attachments = get_posts( $args );
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).

<?php
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); 
$attachments = get_posts( $args );
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 ) {
	echo 'ID on the first post found ' . $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.

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

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.

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.

Change Log

Source File

get_posts() is located in wp-includes/post.php.

Related

See also index of Function Reference and index of Template Tags.