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

[html]<?php
$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;
$args=array(
‘category__in’ => $category_ids,
‘post__not_in’ => array($post->ID),
‘posts_per_page’=>4,
‘caller_get_posts’=>1
);
$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() ) {
$my_query->the_post();?>
<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); ?>
</a>
<?php endif; ?>
<a href="<?php the_permalink(); ?>"><h6><?php the_title(); ?></h6></a>

</div>
<?
}
echo ‘</div>’;
}
}
$post = $mypost;
wp_reset_query();
?>[/html]

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 *