Display Related Posts by Tags

Show related posts based on the tags of the current post.

<?php
function display_related_posts() {
    if (is_single()) {
        $tags = wp_get_post_tags(get_the_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(get_the_ID()),
                'posts_per_page'   => 5,
                'caller_get_posts' => 1
            );
            $related_posts_query = new WP_Query($args);

            if ($related_posts_query->have_posts()) {
                echo '<div class="related-posts">';
                echo '<h3>Related Posts</h3>';
                echo '<ul>';
                while ($related_posts_query->have_posts()) {
                    $related_posts_query->the_post();
                    echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
                }
                echo '</ul>';
                echo '</div>';
                wp_reset_postdata();
            }
        }
    }
}
add_action('wp_footer', 'display_related_posts');

Post Comment