Show Related Post According to Category in WordPress

In our previous tutorial we have shown you how you can show related posts without using any plugin in your WordPress blog. They query is based on tags i.e the query will find out related posts by matching the tags. Now there are many post might not having same tags but same category. So if you want to show related posts according to category in WordPress site or blog then you need to modify that query. Here is the query:

Show Related Post Without Using Any Plugin in WordPress

$mypost = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
‘category__in’ => $category_ids,
‘post__not_in’ => array($post->ID),
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo ‘<div id="home-fpost" class="grid col-940">
<h1 class="rposts" align="center">Check Some Related Posts</h1>’;
while( $my_query->have_posts() ) {
<div class="<?php if( ++$last_class_counter1 %4 == 0) echo ‘grid col-220 fit’; else echo ‘grid col-220’; ?>">

<?php if( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail(240,180); ?>
<?php endif; ?>
<a href="<?php the_permalink(); ?>"><h6><?php the_title(); ?></h6></a>

echo ‘</div>’;
$post = $mypost;

Just copy paste above code in your theme’s single.php file. If your are having any problem with CSS then check previous tutorial to show related post by using tags. Or comment below and we will defiantly try to help you.

Author: mytutorialguru

Share This Post On

Submit a Comment

Your email address will not be published. Required fields are marked *