More from this category using WordPress

Keeping readers to your website entertained can be a tricky thing to do, i certainly haven’t got enough interesting content to keep a reader looking around and re-visiting to check on what’s new. That aside, i useĀ ”More from this category” and “Recent Related Articles” blocks of code on as many pages of my site as i can as if somebody come’s across my site looking for “How to add the thumbnail path to the WordPress Media Uploader” i know they may also be interested in “How to do something kinda cool with WordPress that makes you more awesome”.

Below is the code i use for the “More from this category” on the right hand side, if you would like to use it simply add it at any point you wish within your sidebar.php file that resides in your themes directory (e.g. /themes/mythemename/comments.php).

<?php
if ( is_single() ) :
global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
<li><h2>More from this category</h2>
<ul class=”bullets”>
<?php
$posts = get_posts(‘numberposts=10&category=’. $category->term_id);
foreach($posts as $post) :
?>
<li><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></li>

<?php endforeach; ?>

<li><strong><a href=”<?php echo get_category_link($category->term_id);?>” title=”View all posts filed under <?php echo $category->name; ?>”>Archive for ‘<?php echo $category->name; ?>’ &raquo;</a></strong></li>
</ul>
</li>
<?php endforeach; endif ; ?>

A quick explanation
Starting at the beginning, this piece of code will initially check to see whether it is running on a “single” page, meaning it checks to see if it is on an article/blog page (not the front page, or a static page). It then get’s the category of the current page and requests 10 more of the most recent posts from the same category (numberposts=10, this can be changed to whatever you like). After that it uses a loop to display each link, and after all that it will display a link to the “Archive” for that category just in case the displayed articles aren’t interesting enough.

CSS
As can be seen, the code uses the class “bullets” for styling, here is the CSS i use which you could copy into your style.css file and modify to suit your theme. If you already have a “bullets” class you can of course rename the class in the PHP code above to something else.

.bullets li {
background: url(images/sidebar-bullet.gif) no-repeat !important;
padding-left: 16px !important;
}

If anyone would like to know how to do this using Images (like in my “Recent Related Articles” section on every page, then drop me a comment and ask me to post the code. I would be more than happy to do it, but am just not sure if anyone actually needs it.

Tags: