Top 10 Latest Posts in WordPress


This guide will help you to fetch the Top 10 latest Posts/Articles in WordPress. The orderby clause in WP_Query class will help to fetch the latest published posts on a WordPress website. Displaying the latest published posts help website user to navigate the recently published posts by the author easily.

Display Top 10 Latest Posts in WordPress

Articles that may interest you…

The following steps will help to fetch the top 10 latest posts in WordPress.

Step 1: The first step is to, prepare the custom query using the WP_Query class.

<?php
    $latest_posts = new WP_Query(array(
		'posts_per_page' => 10,
        'orderby' => 'date'
    ));
?>

orderby » Sort retrieved posts by parameter. The default is the date (post_date).

posts_per_page » Fetches the number of posts you have specified.

Step 2: Do a check whether the result contains posts or not.

<?php if ($latest_posts->have_posts()) : ?>

Step 3: If it contains posts, loop through it.

<?php while ($latest_posts->have_posts()) : $latest_posts->the_post(); ?>

    <a href="<?php the_permalink(); ?>" class="list-group-item">
	
	<?php the_title(); ?> 
	
	</a>
<?php endwhile; ?>

Step 4: Restore/reset the WordPress query to the normal flow.

<?php wp_reset_postdata(); ?>

wp_reset_postdata() function restores the $post global to the current post in the main query.

Step 5: Close if-else block.

<?php else : ?>
<?php endif; ?>

See the complete example.

<div class="list-group mb-3">

    <h4 class="list-group-item font-italic bg-light">New 10 Articles</h4>
    <?php
		$latest_posts = new WP_Query(array(
            'posts_per_page' => 10,
            'orderby' => 'date'
    ));
    ?>
    <?php if ($latest_posts->have_posts()) : ?>
	
        <?php while ($latest_posts->have_posts()) : $latest_posts->the_post(); ?>
		
			<a href="<?php the_permalink(); ?>" class="list-group-item">
			<?php the_title(); ?>
			</a>
			
        <?php endwhile; ?>
		
        <?php wp_reset_postdata(); ?>
		
    <?php else : ?>
    <?php endif; ?>
</div>

References

  1. WP_Query
  2. wp_reset_postdata()
  3. WP_Query – Order & Orderby Parameters

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.