Show the three latest posts with WP_Query

Description: In the front-page.php of a theme, show a list (ul) of the titles of the three latest posts, each as a link.

Hint:

  • Use new WP_Query( array( 'posts_per_page' => 3 ) ).
  • Call wp_reset_postdata() at the end.

Solution

<?php get_header(); ?>
<?php $latest = new WP_Query( array( 'posts_per_page' => 3 ) ); ?>
<ul class="latest">
<?php while ( $latest->have_posts() ) : $latest->the_post(); ?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_postdata(); ?>
</ul>
<?php get_footer(); ?>
Terminal output

$ curl -s http://example.com/ | sed -n '/<ul class="latest">/,/<\/ul>/p'
<ul class="latest">
<li><a href="http://example.com/post-four/">Post four</a></li>
<li><a href="http://example.com/post-three/">Post three</a></li>
<li><a href="http://example.com/post-two/">Post two</a></li>
</ul>

How it works

  • WP_Query gets the newest three posts, because the default order is by date, newest first.
  • the_post() sets the data of each post, so the_title() and the_permalink() work.
  • wp_reset_postdata() gives the global post data back.

Read WP_Query.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.