WordPress related articles by tags and/or categories

Here is a quick code snippet for displaying any given number of articles, related first by tags and optionally from the same category. This is by no means definitive solution, but might come in handy as a quick start.

Drop this inside the loop in single.php template, I suggest right behind the the_content() call. See it in action on the live site.

Use it as a base for more advanced features, or simply c/p. It’ll work :)

<?php
    
    $max_articles = 7;  // How many articles to display
    
    echo '<div id="related-articles" class="sidebox"><h3>Related articles</h3><ul>';
    
    $cnt = 0;
    
    $article_tags = get_the_tags();
    $tags_string = '';
    if ($article_tags) {
        foreach ($article_tags as $article_tag) {
            $tags_string .= $article_tag->slug . ',';
        }
    }

    $tag_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&tag=' . $tags_string);
    
    if ($tag_related_posts) {
        foreach ($tag_related_posts as $related_post) {
            $cnt++; 
            echo '<li class="child-' . $cnt . '">';
            echo '<a href="' . get_permalink($related_post->ID) . '">';
            echo $related_post->post_title . '</a></li>';
        }
    }


    // Only if there's not enough tag related articles,
    // we add some from the same category
    
    if ($cnt < $max_articles) {
        
        $article_categories = get_the_category($post->ID);
        $category_string = '';
        foreach($article_categories as $category) { 
            $category_string .= $category->cat_ID . ',';
        }
        
        $cat_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&category=' . $category_string);
        
        if ($cat_related_posts) {
            foreach ($cat_related_posts as $related_post) {
                $cnt++; 
                if ($cnt > $max_articles) break;
                echo '<li class="child-' . $cnt . '">';
                echo '<a href="' . get_permalink($related_post->ID) . '">';
                echo $related_post->post_title . '</a></li>';
            }
        }
    }
    
    echo '</ul></div>';
     
?>

Marko Dugonjić is a designer specialized in user experience design, web typography and web standards. He runs a nanoscale user interface studio Creative Nights and organizes FFWD.PRO, a micro-conference and workshops for web professionals.

Interested in more content like this?