How To Show Recent Posts On WordPress

Quick Summary
- Fetch posts with get_posts() and loop over them with setup_postdata() to show recent posts anywhere in a theme, such as a sidebar.
- The snippet shows 4 posts ordered by menu_order, so set orderby to date and order to DESC to list the newest posts first.
- Use posts_per_page set to -1 to show every post, and reset the global $post after the loop with wp_reset_postdata() or wp_reset_query().
This code helps you show recent posts anywhere in a WordPress theme, for example on the homepage or in a sidebar. It fetches posts with get_posts() and loops over them, leaving a spot for your own HTML. It shows 4 posts; to show all posts, use 'posts_per_page' => -1. As written it sorts by menu order, so change the order as shown at the end to list the newest posts first.
Put it in a theme template file, such as front-page.php, sidebar.php or a page template, ideally in a child theme.
<?php
global $post;
$args = array(
'post_type' => 'post',
'posts_per_page' => 4,
'orderby' => 'menu_order',
'order' => 'ASC',
);
$myposts = get_posts($args);
foreach($myposts as $post):
setup_postdata($post);
?>
<!-- HERE YOU ADD YOUR POST BLOCK -->
<?php endforeach; wp_reset_query(); ?>How it works
$argssets up the query:post_typeispost, andposts_per_pagelimits the number of results.global $postandsetup_postdata( $post )let template tags such asthe_title(),the_permalink(),the_excerpt()andthe_post_thumbnail()work for each post. Use them where theHERE YOU ADD YOUR POST BLOCKcomment is.wp_reset_query()restores the global$postafterwards, so the rest of the page shows the right data.wp_reset_postdata()is the function meant for this case;wp_reset_query()calls it internally, so both work.
The same code on GitHub Gist
The snippet is also available as a Gist:
<?php
global $post;
$args = array(
'post_type' => 'post',
'posts_per_page' => 4,
'orderby' => 'menu_order',
'order' => 'ASC',
);
$myposts = get_posts($args);
foreach($myposts as $post):
setup_postdata($post);
?>
<!-- HERE YOU ADD YOUR POST BLOCK -->
<?php endforeach; wp_reset_query(); ?>Show the newest posts first
Both versions order by menu_order. Regular posts all have a menu order of 0, so this doesn’t sort them by date. For the latest posts first, change the arguments to 'orderby' => 'date' and 'order' => 'DESC'.
On a single post page you may also want to leave out the post being read: excluding the current post with post__not_in adds one argument for that.
Related articles
- a latest posts query with WP_Query: sorted by date, with a fallback featured image
- reading post data without setup_postdata(): the same get_posts() loop without changing the global post

