up
close

using an older version of IE, huh?

We no longer support older version of Internet Explorer on kohv3. For a better experience try upgrading to a newer version of Internet Explor, Firefox or Chrome.

kohv3 will work in older version but for an enhanced experience, we recommend you upgrade.

close client login

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:

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:

have_posts()) {
 while ($my_query->have_posts()) : $my_query->the_post();
?>
 
	
 

	

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('//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):

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();
?>

 
	
 

	

If you want to learn more about this hack and utilizing it with Tags then check out this post from WP Recipes.

more posts in: PHP, web development, WordPress Hacks
comments