Warning: Your browser is very out-of-date. You should upgrade to a better browser.

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

in Belfast, Northern Ireland

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.

Contact me today!

WordPress

WordPress is fast, flexible, responsive and open source. Your WordPress site can be built from the ground up to be fast, accessible and search engine friendly.

About WordPress · WordPress Posts

Related WordPress Posts

WordPress October 2020

WordPress - Rename the Posts section in Admin

The PHP script below can be added to the WordPress Theme functions.php file. It will rename the standard "posts" section to "stories". Replace 'stories'/'story' with...
WordPress August 2020

Notes on Transferring a WordPress site to AWS

Some notes on transferring an existing WordPress site to Amazon Web Services and some common issues. ## MySQL Import Fail If the import fails on...
WordPress November 2019

WordPress Security - Nginx Hardening

Techniques for hardening WordPress Sites running on an Nginx server to enhance security. ## Limit Access to Admin Panel ### Limit XMLRPC Access This will...

More WordPress Posts...