Written on November 24, 2011  /  with 3 comments  /  in the Wordpress Tips category.

Display Recent Posts Based On The Category Assigned To The Current Post – WordPress Trick

Not sure if that title makes sense or not. Basically the idea is this: you want to display in your sidebar the most recent posts in your blog, but more specifically the most recent posts for a category. And even more specifically than you want it to be dynamic so that it’s always the same category of the current post someone is reading.

note: I’m realizing as I’m writing this that this is one of the most difficult WordPress things I have ever tried to explain. Yikes!

So to make this happen we need a little PHP. Here’s what I did.

In my Sidebar.php file I used this code:

<?php
  global $post;
  $category = get_the_category($post->ID);
  $category = $category[0]->cat_ID;
  $myposts = get_posts(array('numberposts' => 10, 'offset' => 0, 'category__in' => array($category), 'post__not_in' => array($post->ID),'post_status'=>'publish'));
  foreach($myposts as $post) :
  setup_postdata($post);
?>
    <li>
      <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php endforeach; ?>
<?php wp_reset_query(); ?>

As you can see the code is grabbing the category of the current post that is being viewed. It’s then setting up a simple wordpress loop to show the most recent posts with a title and link. You can change the number of how many recent posts are shown by changing the ‘numberposts’ => 10, to whatever number you like.

See Demo = look at my sidebar to the right for the widget titled “Recent Posts From This Category.”

Hope this helps. I know with all of the Google Panda updates this year have had many bloggers looking for new ways to make their sidebars more dynamic. This is a great way to help you do that.

3 responses to this article so far...

Leave a comment