WordPress: the get_posts() function in depth

The get_posts() WordPress function is one of the many template functions (used to retrieve posts and create Loops) which are directly derived from the more extended WP_Query class. In this article we'll take an in-depth look to this function.

get_posts() can be found in the wp-includes/post.php file of the WordPress core. It looks like this:

function get_posts($args = null) {
	$defaults = array(
		'numberposts' => 5, 'offset' => 0,
		'category' => 0, 'orderby' => 'post_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);

}

Defaults parameters include:

  • 'numberposts' - Default is 5. Total number of posts to retrieve.
  • 'offset' - Default is 0. The number of posts you want to skip.
  • 'category' - What category to pull the posts from.
  • 'orderby' - Default is 'post_date'. How to order the posts.
  • 'order' - Default is 'DESC'. The order to retrieve the posts.
  • 'include' / 'exclude' - Posts to be excluded or included in the newly created Loop.
  • 'meta_key' - The name of a post custom field.
  • 'meta_value' - The value of a post custom field.
  • 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
  • 'post_parent' - The parent of the post or post type.
  • 'post_status' - Default is 'publish'. Post status to retrieve.

This function can be used as follows:

<?php
$args = array( 'numberposts' => 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; ?>

get_posts() uses the WP_Query::query() method to execute its query against the database. If you need more control over the Loop you're creating, consider using the WP_Query class directly.

Back to top