WordPress: How To Show Related Posts By Tag With Thumbnail

By Focusoncode May 18, 2018

Related posts is an important section in any website because it takes user from page to page, deep in your website, exploring your awesome content.

Related posts can be filtered even by categories but results from tags can be more accurate. Below you will find the code that gets 4 related posts of single article by tags.

Related posts by multiple tags

<?php
//for use in the loop, list 4 post titles related to tags on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$ids = array();
foreach ($tags as $tag) {
$ids[] = $tag->term_id;
}
$args=array(
'tag__in' => array($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 '<ul class="related_posts">';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_post_thumbnail(); ?></a>
<h3><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
</li>

<?php
endwhile;
echo '</ul>';
}
wp_reset_query();
}
?>

The above code will get 4 posts related to the tags specified in the current posts that user is viewing.

However if you want to show 4 posts of first tag of the current post, all you have to do is remove tags foreach loop and get only the first tag. Take a look at the code below:

Related posts by single tag

<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$tag_id = $tags[0]->term_id;
$args=array(
'tag__in' => array($tag_id),
'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 '<ul class="related_posts">';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_post_thumbnail(); ?></a>
<h3><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
</li>

<?php
endwhile;
echo '</ul>';
}
wp_reset_query();
}
?>

With the above code you can show 4 related posts containing the first tag of the current post.

Share This

Leave a Comment

Your email address will not be published.