WordPress Hacks: Related Category Post in WordPress
With a recent project, I wanted to display recent posts, of the same category, on the page. After trying a whole bunch of plugins and not being satisfied I did a little research and testing and made this up. It works pretty well for my needs, but as you’ll see, it is quite flexible, and can be utilized for not only categories, but tags also. Quick note, all this code goes inside the loop!
First step was to get the current category, in my case, I wanted the parent category. I used the following to store the category in a variable:
<?php
$category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
$parent = $category[0]->cat_name;
?>
You can echo that out to make sure it’s what you’re expecting. After that, we need to call a WP_Query to get the related posts. I used the following to get 3 posts of the same parent category to display:
<?php
$my_query = new WP_Query('showposts=3&category='.$parent);
if ($my_query->have_posts()) {
while ($my_query->have_posts()) : $my_query->the_post();
?>
<div>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><img src="<?php echo catch_that_image(); ?>" width="165" /></a>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
</div>
<?php
endwhile;
}
If you’re wondering what that “catch_that_image” code is, you can view the WordPress support forum or you can insert the following into your functions.php file:
// Get URL of first image in a post
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
}
Or you can just completely forget about it. That nice little functions allows you to grab the first image of a post and display in as you which. As for the related categories, here is the full code I used (inside the loop):
<?php
$category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
$parent = $category[0]->cat_name;
$my_query = new WP_Query('showposts=3&category='.$parent);
if ($my_query->have_posts()) {
while ($my_query->have_posts()) : $my_query->the_post();
?>
<div>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><img src="<?php echo catch_that_image(); ?>" width="165" /></a>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
</div>
<?php
endwhile;
}
If you want to learn more about this hack and utilizing it with Tags then check out this post from WP Recipes.




Cindy on June 5th, 2010 -
This is exactly what I am looking for but I am a total beginner and have no idea where I paste the code. Any way you can explain that?