The most appropriate use for get_posts() is to create an array of posts based on a set of parameters.

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 get_pages() but are implemented quite differently. get_posts() uses WP_Query, whereas get_pages() queries the database more directly. Each have parameters that reflect this difference in implementation.

get_posts() uses WP_Query parameters.

Don’t forget to use wp_reset_postdata() after the loop if using with setup_postdata() to reset global variables to the main query.


$args = array(
	'posts_per_page'   => 5,
	'orderby'          => 'date',
	'order'            => 'DESC',
	'post_type'        => 'post',
	'post_status'      => 'publish'

$posts_array = get_posts( $args );

Basic Example

In my example below, I will query 5 posts from article post type and loop them using foreach. I then pass the $post variable into setup_postdata() function to fill the global variables so we can use the template tags like the_title, the_permalink, the_content() inside the loop.

$args = array( 'posts_per_page' => 5, 'post_type' => 'article' );

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
		<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endforeach;
wp_reset_postdata(); ?>