Displaying the recent posts is a very common functionality in WordPress. Most of this functionality can be found in the homepage of many blog sites. Because of its very common usage, WordPress has a native function for this called wp_get_recent_posts().

Today, I will show you how to do this using wp_get_recent_posts(), get_posts(), and WP_Query class.

Method #1: Using wp_get_recent_posts()

This function will accept two parameters, the first is the arguments, and the second is the output type which is either OBJECT, ARRAY_A. The default output is ARRAY_A.

<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
if($recent_posts) : ?>
	<ul>
		<?php foreach( $recent_posts as $recent ){
			echo '<li><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </li> ';
		} ?>
	</ul>
<?php endif; ?>

wp_get_recent_posts() uses the get_posts() function so if you wanted to add more arguments, you can use the same arguments with get_posts().

Method #2: Using get_posts()

This is very common. Many developers prefer to use this method than the first one.

<?php
$args = array( 'numberposts' => '5', 'orderby' => 'date', 'order' => 'DESC' );
$recent_posts = get_posts( $args );
if($recent_posts) : ?>
	<ul>
		<?php foreach ($recent_posts as $post) :
		   setup_postdata($post); ?>
		   <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
		<?php endforeach; wp_reset_postdata(); ?>
	</ul>
<?php endif; ?>

Method #3: Using WP_Query class

This method is what I used most.

<?php
$args = array( 'posts_per_page' => '5', 'orderby' => 'date', 'order' => 'DESC' );
$query = new WP_Query($args);
if($query->have_posts()) : ?>
	<ul>
		<?php while($query->have_posts()) : $query->the_post(); ?>
            <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
		<?php endwhile; wp_reset_postdata(); ?>
	</ul>
<?php endif; ?>