Get Related Posts by TAGS in WordPress without Plugin

In my last tutorial i have described how to get related posts by category. In this post i will show you to get related posts by Tags without any plugins, keeping everything simple, light and accessible.

Lets say we want to add a related posts section at the end of each blog post we create. After each post we will insert 5 related posts that will be determined based on their content. To decided which articles are related, we will compare the articles’s “tags.”

Let’s get started!

 
$tags = wp_get_post_tags($post->ID);

if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;

$args=array(
'tag__in' 				=> $tag_ids,
'post__not_in' 			=> array($post->ID),
'showposts'				=>5,
'ignore_sticky_posts'	=>1
);

$my_query = new WP_Query($args);

if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" class="postlistlink" rel="bookmark"><?php the_title(); ?></a>
<?php
endwhile;
}
wp_reset_query();

}

So simple right. Still if you have any problem to understand, just drop a message below.
Thanks.

This post has already been read 2642 times!

Mehedi Hasan

Cool WordPress Developer having much agile experience to develop any kind of WordPress sites & plugins. Also good in troubleshooting, fixing & making any kind of tweaks for WP site.

More Posts

Mehedi Hasan

Cool WordPress Developer having much agile experience to develop any kind of WordPress sites & plugins. Also good in troubleshooting, fixing & making any kind of tweaks for WP site.

2 thoughts on “Get Related Posts by TAGS in WordPress without Plugin

  • September 25, 2019 at 2:55 pm
    Permalink

    Hi Mehedi … I am currently using an index.php template page with Bootstrap 4 to list posts with excerpt. But, I now wish to split the display by “category-slug” or by “tag_id”. I have no problem getting the posts by “category-slug” or by “tag_id”. The page works just, except for one small problem: I am unable to set the pagination correctly with the “$counter” variable. The “$counter” variable works perfectly with the “all posts” display. But, it does not work correctly when I try to display the posts by “category” or “tag”. If you could give me some suggestions, I would be much obliged. Let me know if you want me to send you the code that I am using in each case.
    Regards … Derek

    • October 2, 2019 at 9:17 pm
      Permalink

      Hi Derek,
      You need to add paged parameter. Please check here https://codex.wordpress.org/Pagination and hope you can find all the solutions about $paged for pagination. Thanks

Comments are closed.