Caution: This post was published in 2016 and may contain information, techniques, or code examples that are no longer current. Please double-check official documentation and modern best practices before using anything from this article.

PHP: Use WordPress blog tags to find related posts

A simple script that can be used to pull related-type posts for a WordPress blog post. The related aspect is based on the fist tag assigned to the post. The script will return at most 5 other posts from the site that also include the first tag.

<?php

$tags = wp_get_post_tags($post->ID);

if ($tags) {
    
    $first_tag = $tags[0]->term_id;
    
    $select = array(
       'tag__in'          => array($tags[0]->term_id),
       'post__not_in'     => array($post->ID),
       'posts_per_page'   => 5,
       'caller_get_posts' => 1
    );
    
    $tag = get_tag($first_tag);
   
    $tag_query = new WP_Query($select);
   
    if( $tag_query->have_posts() ) {
        echo "<ul>";
        while ($tag_query->have_posts()) : $tag_query->the_post(); ?>
            <li>
                <a href="<?php the_permalink() ?>">
                   <?php the_title(); ?>
                </a>
            </li>

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

?>

WordPress developer

<p>
  in Belfast, Northern Ireland
</p>

I’ve been developing WordPress websites for 10 years and am always looking for the next exciting project from personal blog, community portal or business website. Why not get in touch to see if I can help you with yours.

<p>
  <a class="button" href="/contact/">Contact me today!</a>
</p>

Ready to elevate your WordPress site?

Whether you're launching a new site, strengthening security, or integrating WooCommerce, I can help transform your vision into a high-performing online presence.

Contact me to discuss your WordPress project

More WordPress posts

Using WordPress as a static site generator

Static site generators have gained significant traction amongst developers, designers, and businesses seeking faster, more secure websites. Unlike traditional dynamic sites, which rely on a database to deliver content on…

Continue reading

Moving a WordPress Website with ACF and Custom Post Types to Brightspot CMS

Migrating a website from WordPress to Brightspot CMS can seem daunting, particularly when the WordPress installation relies heavily on Advanced Custom Fields and Custom Post Types. Both ACF amd CPT…

Continue reading

Better WordPress Performance

A slow-loading website can be frustrating, not only for your visitors, but for you as a business owner. If your WordPress site is taking too long to load, you’re not…

Continue reading

What's going on between WordPress and WP Engine?

The disagreement between WordPress and WP Engine has sparked considerable debate within the WordPress community and could have important implications for users of the WordPress content management system (CMS). WP…

Continue reading