Worpdress How to show the last 5 posts

Show the last 5 posts or whatever number you specify using the following code, it loops through all of the posts.

First method I devised:

              <ul id="recent-items">
                  $recentPosts = new WP_Query();
<!--t added set the incremental counter<=? to the number of recent posts you want to see-->
              <?php $counter = 1; while ($recentPosts->have_posts() && $counter <= 10) : $recentPosts->the_post(); ?>
                  <a class="archive-content_footer" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?> - <?php the_date(); ?></a>
                  <?php // the_excerpt() ?>
                  <?php $counter++ ?>
              <?php endwhile; ?>

Second method officially shown on the wordpress codex (however the_date() didn’t work with this for some reason):

              <ul id="recent-items">
             global $post;
             $myposts = get_posts('numberposts=5');
             foreach($myposts as $post) :
    <div id="posttitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?><?php the_date('Y-m-d', '<h3>', '</h3>'); ?></a></div>
 <?php endforeach; ?>

Leave a comment