Show Item By Tags without Plugins

Show related item by tags without using any type of plugins. Use functions code on your theme and show item by tag. So follow simple steps.

How to Do

  • Open theme’s functions.php file and paste given code.
//Show Related item by tags
function single_post_related_items_by_tag() {
$current_post_id = get_the_ID();
$post_tags = get_the_tags($current_post_id);
if ($post_tags) {
$tag_ids = wp_list_pluck($post_tags, 'term_id');
$args = array(
'tag__in' => $tag_ids,
'post__not_in' => array($current_post_id),
'posts_per_page' => 4,
'orderby' => 'rand',
);
$related_query = new WP_Query($args);
if ($related_query->have_posts()) {
echo '<section class="related-posts-tag clear" nosnippet>';
echo '<h3>Related Items</h3>';
echo '<ul>';
while ($related_query->have_posts()) {
$related_query->the_post();
echo '<li><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
echo '</section>';
}
wp_reset_postdata(); // Reset the post data
}
}

Now SAVE functions.php file. Then open single.php file and paste given code, Where you want to show items.

<?php single_post_related_items_by_tag(); ?>
  • Then SAVE single.php file.

Hope this code will work on your theme. Thanks for visiting.