Get Related Post by Category in WordPress without Plugin
Interlinks in your blog articles will allow all types visitors to get related content to the current post. This will help to build up page views on your blog and build most visitor engagement.
But it is time consuming to engage visitors if you do not have proper links in blog to pick the related post. So you have to make sure you link correctly to related posts. And WordPress have algorithm that would find other posts within the same category as the current post, and it will list them as related posts.
Every post that you put up on your blog should have a one or multi category. Therefore if you can match these category to other blog posts you will easily be able to find posts which are similar to the current post.
The below code uses post’s category as a criteria to fetch out the similar posts. This is really useful if each of your post belongs to at-least one category. Using this, you can ensure that all the displayed related posts would belong to the same category, this would improve the on page seo too.
<?php $catArgs = array( 'category__in' => wp_get_post_categories($post->ID), 'showposts' => 5,//display number of posts 'orderby' =>'rand',//display random posts 'post__not_in' => array($post->ID) ); $cat_post_query = new WP_Query($catArgs); if( $cat_post_query->have_posts() ) { while ($cat_post_query->have_posts()) : $cat_post_query->the_post(); ?> <li> <a href="<?php the_permalink() ?>"> <?php the_title(); ?></a></li> <?php endwhile; wp_reset_query(); } ?>
Still if you have any problem to set up, please drop a message bellow. Hope we can solve your any problem.
Thanks.
This post has already been read 5129 times!
Thank you soooo much for this code!
I’m trying to put it on a widget thru PHP Code Widget plugin.
It seems to work fine but I can’t reach any URL.
Could I fix this issue?
Thank you
hi, thank you for share that code,
sorry, maybe you need fix a bit
<a href="”>
seems should be like this :
<a href="”>
regards
Thanks @silvia.
I just fixed it 🙂
// to // without !
Nice tutorial, thanks a lot bro!
Hi, is it possible to limit them by date? Show only those of the last year?
Hi Luigi,
This is possible by adding Date Query in arguments :
“`
$catArgs = array(
‘category__in’ => wp_get_post_categories($post->ID),
‘showposts’ => 5,//display number of posts
‘orderby’ =>’rand’,//display random posts
‘post__not_in’ => array($post->ID),
‘date_query’ => array(
array(
‘year’ => 2018,
‘month’ => 12,
‘day’ => 30,
),
),
);
“`
Hope this helps 🙂