A lot of themes these days comes with the Recent Posts code added already. It’s a basic list, usually just set to display the last 5 or 10 posts. A nice list but are you making the most of it?

Remove the current Post

A recent posts list comes into its own when the user is on a single post page. It allows them to see the most recent posts you’ve written on the site. However, if the page they’re on happens to be on that list then you’ve wasted a slot on the list. So why not just remove it? If we take the (usually) default code to list recent posts of:

[sourcecode language=”php”]< ?php $myposts = get_posts('numberposts=5'); foreach($myposts as $post) : ?>

  • “>< ?php the_title(); ?>
  • < ?php endforeach; ?>[/sourcecode]

    Recent Posts from current Category

    The above code displays the recent posts from all categories. A friend of mine recently said how he wanted to restrict the posts to displaying just the last 5 posts from the category of the post that the user is currently viewing. For example, if you had a category called ASP and another called PHP, if someone views a post on PHP they’d probably be more interested in the last 5 posts from the PHP category than from both, well I know I would 😉

    To do this we need to work out the category ID of the current post, and then restrict the recent posts to that category. We use the get_the_category() function, to get details of the category that the post is currently in. The code to do this is

    [sourcecode language=”php”]$catchk = “”;
    if (is_single()) :
    $cat = get_the_category();
    $catID = $cat[0]->cat_ID;
    $catchk = “&category=”.$catID;
    endif;[/sourcecode]

    Line 1 just sets the variable to empty so that we don’t get any PHP warnings. Then we check if we’re on a single post. If so, we get the category details, and then we get the category ID of the first category (note, for multiple categories, this code will only take the first category from the list). Then we change the $catchk variable to include the category parameter for the get_posts() function. We then add this into our get_posts function too ie.

    $myposts = get_posts('numberposts=5&exclude='.$postid.$catchk);

    Of course, if we’re restricting our recent posts to a specific category then it may be a good idea to add the category name into the recent posts title. So we can get the name when we’re getting the ID of the category, and simply add this into the title.

    So our final code would be

    [sourcecode language=”php”]< ?php $postid = 0; $catchk = $rptitle = ""; if (is_single()) : $postid = $post->ID;
    $cat = get_the_category();
    $catID = $cat[0]->cat_ID;
    $rptitle = ” from “.$cat[0]->cat_name;
    $catchk = “&category=”.$catID;
    endif;
    ?>

    Recent Posts< ?php echo $rptitle ?>

      < ?php $myposts = get_posts('numberposts=5&exclude='.$postid.$catchk); foreach($myposts as $post) : ?>

    • 60

      SHARES