When using WordPress as your CMS of choice, there often becomes a need to display a list of recent blog posts on a non-blog page (such as a static homepage). The recent blog posts list is useful as it enable users to get a snapshot of what is going on in your blog, without actually having to visit the page.

There are two ways I explored to solve this particular problem:

  • Short code that can be placed anywhere
  • Snippet of code that sits directly in your template page file

This article will explore both ways.

Short code

The shortcode way is useful. The shortcode will enable you to insert the blog summary list anywhere you wish, just by typing the shortcode in.

First stage is to create a new plug-in. To do this, create a new folder in your plug-ins directory and give it a nice name such as “recent-posts”. Inside this directory, create a new .php file and call it the same as the directory name.

Inside this .php file we need to define the module. Copy in the following lines:

/*
Plugin Name: adamrob-recent-posts
Plugin URI: http://www.adamrob.co.uk
Description: Shows recent posts on home page
Version: 0.1
Author: adamrob.co.uk
Author URI: http://www.adamrob.co.uk
*/

This tells wordpress what the module is, who the author is and some extra meta type data.

Next, we want to create the function that will generate our recent blogs list HTML. Copy the following code in:

function adamrob_recentposts_fc( $atts ) {
 
    // Attributes
    extract( shortcode_atts(
        array(
            'noposts' => '3',
            'blogpageid' => '81',
        ), $atts )
    );
 
    // Code
    $output = '<div id="outer" style="width:100%; text-align:center; margin: 15px 0px 15px 0px;">';
    $output = $output . '<h2><a href="' . get_page_link($blogpageid) . '" title="Visit the blog">From The Blog</a></h2>';
 
    $args = array( 'numberposts' => $noposts );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        $output = $output . '<div style="width:60%; margin: 0px 0px 0px 0px; display: inline-block; clear:left;">' . '<hr />';
        $output = $output . '<div id="img" style="float:left; margin-right:15px;">' . get_the_post_thumbnail($recent['ID'], 'thumbnail') . '</div>';
        $output = $output . '<p><strong>' . '<a href="' . get_permalink($recent["ID"]) . '" title=' . $recent["post_title"] . ' >' . $recent["post_title"] . '</a> ' . '</strong></p>';
        $output = $output . '<p>' . mysql2date('j M Y', $recent["post_date"]) . '</p>';
 
        $output = $output . substr($recent["post_content"], 0 , 350) . '...'; 
        $output = $output . '<a href="' . get_permalink($recent["ID"]) . '" title="Read More '.$recent["post_title"].'" >' . 'Read More'.'</a>';
 
        $output = $output . '</div><br />';
    }
    $output = $output . '</div>';
 
    //Return the result
    return $output;
}

This function does the following:

  • Gets the attributes (if any) that were passed into the function via the shortcode. This also writes default values if no parameter was passed in, or less then specified.
  • Uses the $output variable to store the generated HTML. This variable will then be returned at the end.
  • Set up a
    <div>

    to style the layout. My layout is rather basic, but you can experiment here to achieve the style you require.

  • Get the array of blog posts using the WordPress function
    wp_get_recent_posts( $args )
  • Loop through the posts and extract the data that we want, then render it in some html tags. In my code, I am using the following WordPress functions:
    • get_the_post_thumbnail($recent[‘ID’], ‘thumbnail’) to return the posts thumbnail image.
    • get_permalink($recent[“ID”]) returns the posts ID number for linking to.
    • $recent[“post_title”] returns the posts title.
    • mysql2date(‘j M Y’, $recent[“post_date”]) returns the posts datetime and displays it in a format of choice.
    • substr($recent[“post_content”], 0 , 350) returns the posts content, but limits it to 350 characters. this gives us the “summary”.
  • The $output variable (that contains all our generated HTML code) is returned

Thats all the hard stuff done. Now to make it work, we just need to register our shortcode:

//Add the shortcode trigger
add_shortcode( 'adamrob-recentposts', 'adamrob_recentposts_fc' );

This line of code tells WordPress that when it sees the code “adamrob-recentposts” in any of its pages/post, it should execute the function “adamrobrecent_posts_fc”

Activating the plug-in

Now you have completed the code required, we need to enable the plug-in.

In your WordPress dashboard, click the plug-in link. In your list of plug-ins, you will see a new entry for the code you just created. Go ahead and activate it.

Your plug-in is now active, so the final piece of the jigsaw is to find a page where you wish to display the list, and copy in the shortcode

[adamrob-recentposts noposts="3" blogpageid="81"]

In-Line code

Another way to accomplish the exact same task is to code it ‘in-line’ in your template. A simple example is to put the code into ‘footer.php’ so the summary always shows on every page that shows the templates footer.

Using this method you have greater control over styling, as you know exactly where it is going to go, and how you will want it to look.

Implementation is arguably simpler too. Just copy the following code where you wish the summary to be displayed:

<!--
** Recent Posts display on page
** 19JUN2014 by adamrob.co.uk
-->
<!-- Start recent posts implentation -->
<div id="outer" style="width:100%; text-align:center; margin: 15px 0px 15px 0px;">
    <h2><a href="<?php echo get_page_link(81); ?>" title="Visit the blog">From The Blog</a></h2>
    <?php
        $args = array( 'numberposts' => '3' );
        $recent_posts = wp_get_recent_posts( $args );
        foreach( $recent_posts as $recent ){?>
            <div class="blog" style="width:50%; margin: 0px 0px 0px 0px; display: inline-block;">
                <hr />
                <div id="img" style="float:left; margin-right:15px;">
                    <?php echo get_the_post_thumbnail($recent['ID'], 'thumbnail'); ?>
                </div>
                <p><strong>
                    <?php echo '<a href="' . get_permalink($recent["ID"]) . '" title=' . $recent["post_title"] . ' >' . $recent["post_title"] . '</a> '; ?>
                </strong></p>
                <p><?php echo mysql2date('j M Y', $recent["post_date"]); ?></p>
 
                <?php echo '' . substr($recent["post_content"], 0 , 250) . '...'; ?>
                <span class="link"><?php echo '<a href="' . get_permalink($recent["ID"]) . '" title="Read More '.$recent["post_title"].'" >' . 'Read More'.'</a> '; ?></span>
            </div>
    <?php } ?>
</div>
<!-- End recent posts implementation -->

Those with a keen eye will see the above code is very similar to the code in the shortcode section. That’s because it is the same, with just a few subtle differences. The code will generate the exact same output, but the way it is generated is slightly different. The difference here is that the code is HTML and not PHP. The PHP functions are performed using in-line PHP commands, rather than the shortcode sample that is entirely PHP with the HTML encased into an output variable.

Conclusion

Both ways are just different implementations of the same code. Which way you go entirely depends on your needs. You may prefer the greater control of embedding it into your template, or prefer the flexibility of having it as a shortcode.

The code featured in this article is free to use providing you link back to my site.

Edit – 20SEP2014

It was brought to our attention that the above code will actual show all the most recent blog posts… even if they have not yet been published! The last thing you would want is to show draft posts on your published site.

There is a simple fix however, simply add the post status parameter to the wp_get_recent_posts function:

$args = array(	'numberposts' =&gt; '3',
		'post_status' =&gt; 'publish' );
$recent_posts = wp_get_recent_posts( $args );

There are a raft of other options availble to. Check out the official documentation for more info.