How to add recent posts manually in WordPress

When WordPress came into existence, it was designed to serve people as a blogging platform. It has evolved and became much more than a simple blogging platform, WordPress has become one of the most popular content management systems. Nevertheless, showing recent posts, like in a blog, never lost its importance.

So, how can you show most recent post on your WP page?

If you want to use a sidebar or one of the free WordPress plugins, you can do that easily. But if you want more control over displaying the most recent posts, you might want to consider manually adding the code into WP core files, and in this article, we’re about to show you how to do that.

Add recent posts manually:

Even though you have chosen to add the code manually, you shouldn’t worry about dealing with it. WordPress already comes packed with WP_Query class which allows you to implement the function very easily. Also, the class comes with many customization options and you will need only a few minutes to see how to change the parameters and display recent post like you want them. Let’s start with the basic code:

  1. Open a file where you want your recent post to appear (for example, Main Index Template (index.php))
  2. Copy and paste the following code:
  3. <ul>
    // Define our WP Query Parameters
    <?php $the_query = new WP_Query( 'posts_per_page=10' ); ?>
    // Start our WP Query
    <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    // Display the Post Title with Hyperlink
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    // Display the Post Excerpt
    <li><?php the_excerpt(__('(more…)')); ?></li>
    // Repeat the process and reset once it hits the limit
    <?php
    endwhile;
    wp_reset_postdata();
    ?>
    </ul>
  4. Save changes

If you only want to change the number of recent post to show, simply change the ‘posts_per_page’ number from the 3rd line of the snippet to anything you want. If you want to go more into customization the code, visit WordPress Codex pages.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *