Custom “Latest Posts” Function For Wordpress

While developing my new theme for Wordpress (The one your looking at now!), I came across the need to get the 5 latest blog posts and format the output accordingly. Now, Wordpress has a built in function called wp_get_archives which is great for just getting the latest blog posts and displaying them as is (this function outputs them in a list using <li> tags). However, I wanted to format my list items to have the following CSS classes – first, last and odd.

My first solution was to manually go into wp-includes/general_template.php and hard-code in the code that would do that for me. However, this broke when I upgraded to Wordpress 2.9. Therefore, I have created a new function specific to my theme in wp_content/themes/theme_name/functions.php. I thought this function might come in handy to other developers who are using Wordpress as their content management system, so below is the code.

function latest_posts($limit = 5)
{
    ob_start();
    wp_get_archives("title_li=&type=postbypost&limit=" . $limit);
    $original_content = ob_get_contents();
    ob_end_clean();

    $lines = explode("\n", $original_content);

    $final_content = "";

    for($i = 0; $i < $limit; $i++)
    {
        // Workout the class parameter value
        $class_string = "";
        if($i == 0)
        {
            $class_string = "first";
        }
        else if($i == $limit - 1)
        {
            if(($i % 2) == 1)
            {
                $class_string = "odd last";
            }
            else
            {
                $class_string = "last";
            }
        }
        else if(($i % 2) == 1)
        {
            $class_string = "odd";
        }

        $final_content .= str_replace("<li>", "<li class=\"". $class_string . "\">", $lines[$i]) . "\n";
    }

    echo $final_content;
}

This function takes the output of the wp_get_archives function (by making use of the PHP output buffer, since wp_get_archives echos it’s results rather than return a string), loops through each line (by using explode) and then works out what class names to add to the li element and adds them accordingly. It then echos the modified output and voila.

To use this function, simply call latest_posts() somewhere in your Wordpress template. You can also pass in a numeric parameter to specify the number of posts to return, for example latest_posts(10).

I would love to hear your thoughts/feedback on how this could be improved, or if you have used this and it has helped, let me know in the comments section below!

16 Responses to “Custom “Latest Posts” Function For Wordpress”

Leave a Reply

This site uses KeywordLuv. Enter YourName@YourKeywords in the Name field to take advantage.