Nothing new or groundbreaking here, but for the New Year I have made a commitment to start sharing more of my handy little WordPress snippets as they come up. What you have here is a rather quick and easy way to show related posts based on the category of a single post. This is based on the first category for the post, is to be used on single post pages and assumes that you only use one category per post. As you may notice I would actually write this as a function and call it into my theme via add_action, but you can also extract the necessary pieces of the code for use directly in the theme template files. I have also added a little extra spacing here and there for clarity, edit as you see fit. Please feel free to drop a comment if you have any questions.
<?php
/* theme functions */
add_action('mytheme_secondary_above', 'sidebar_stuff');
function sidebar_stuff() {
if (is_single()) {
global $post;
$category = get_the_category();
$cat = $category[0]->cat_ID;
$my_posts = get_posts('numberposts=5&exclude=' . $post->ID . '&category=' . $cat'); ?>
<ul>
<?php foreach($my_posts as $post) :
setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
<?php
}
}
?>