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
WordPress Themes
WordPress Top Theme List
WordPress Theme Files and Functions
WordPress Template Hierarchy
WordPress Enqueue Scripts and Styles
WordPress Loop
WordPress WP_Query Class
Exercises & Assignments
Build and activate a minimal classic theme
Show the three latest posts with WP_Query
Load a stylesheet with wp_enqueue_style and a version
Show a message only on the front page
Create a child theme which changes the footer
Interview Questions & Answers
What is a WordPress theme?
What are commonly used WordPress theme functions?
Which function is used to get the home URL in WordPress?
Which are the necessary files for a WordPress theme?
What is the use of the wp_head() function in WordPress?
What is the WordPress Loop?
What is the difference between is_home() and is_front_page()?