Display Related Posts with the Highest Number of Common Tags

Related Posts are generally shown based on the current post tags. If you want to show related posts in this way then you have to insert tags in every post those are related to the current post. The tags should be keywords based and not many words, 2-3 words are best.

You may choose one or more tags on every post. It’s very easy to display the related posts from one post tag, but when you choose multiple tags, there probably some tags would not be related to the current post. And if all tags are not close to the post then you see some related posts are actually not related or close to the current post. So, that time you may expect such type of codes which can fill up your expectation.

WordPress does not have any built in codes or function to display related posts with the highest number of common tags. But we can do this by creating a custom database query.

How to Display Related Posts with the Highest Number of Common Tags

The following codes will search the posts in database which contain the highest number of the current post tags and pull them gradually.

Now copy the codes and paste inside single.php of your activated theme directory.

<?php
    global $post, $wpdb;
    $tags = wp_get_post_tags($post->ID);

    if ($tags):
        $tag_ids = array();
        foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
        $number_of_posts = 4; // Number of posts to display
        $query = "
SELECT ".$wpdb->posts.".*, COUNT(".$wpdb->posts.".ID) as q
FROM ".$wpdb->posts." INNER JOIN ".$wpdb->term_relationships."
ON (".$wpdb->posts.".ID = ".$wpdb->term_relationships.".object_id)
WHERE ".$wpdb->posts.".ID NOT IN (".$post->ID.")
AND ".$wpdb->term_relationships.".term_taxonomy_id IN (".implode(",",$tag_ids).")
AND ".$wpdb->posts.".post_type = 'post'
AND ".$wpdb->posts.".post_status = 'publish'
GROUP BY ".$wpdb->posts.".ID
ORDER BY q
DESC LIMIT ".$number_of_posts."";
        $related_posts = $wpdb->get_results($query, OBJECT);
        if($related_posts): ?>
            <div class="related-posts">
                <h2><?php esc_html_e( 'Related Posts:', 'themeslug' ); ?></h2>
                <ul>
                    <?php foreach($related_posts as $post): ?>
                        <?php setup_postdata($post); ?>
                        <li>
                            <div class="thumbnail">
                                <a href="<?php the_permalink(); ?>">
                                  <?php the_post_thumbnail(); ?>
                                </a>
                            </div>
                            <h3>
                                <a href="<?php the_permalink(); ?>">
                                    <?php the_title(); ?>
                                </a>
                            </h3>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif;
    endif;
    wp_reset_query();
?>

Changes: you may need these changes are described below.

  • $number_of_posts: How many posts to display. Change the number according to your need.
  • post_type: You can change the post_type ‘post‘ to any custom post type that you made before.
Note: To display this type of related posts, you will also need to add the same tags are existing in current post to some other posts. Otherwise they will not appear.

Styling the HTML Layout using CSS

Copy the CSS codes and paste into style.css (stylesheet) file.

.related-posts h2 {
    font-size: 18px;
    font-weight: bold;
    padding: 0;
    margin: 0 0 10px;
    line-height: 1.5;
    color: #222
}
.related-posts img {
    height: auto;
    max-width: 100%;
}
.related-posts ul {
    list-style: none;
    padding: 0;
    font-size: 0;
    margin: 0 -5px;
}
.related-posts ul li {
    width: 50%;
    display: inline-block;
    vertical-align: top;
    padding: 0 5px;
    margin-bottom: 10px;
}
@media screen and (min-width: 480px) {
    .related-posts ul li {width: 25%;}
}
.related-posts ul li h3 {
    font-size: 14px;
    padding: 0;
    margin: 5px 0 0;
    line-height: 1.4;
}
.related-posts ul li a {
    color: #222;
    line-height: normal;
    display: block;
    text-decoration: none
}
.related-posts ul li a:hover,
.related-posts ul li a:focus {
    text-decoration: underline;
}

After using the CSS codes above, the result should look like this ─

Display Related Posts with the Highest Number of Common Tags