Related posts display randomly by tag

Some of the code in OP is a bit old and depreciated, like caller_get_posts which was depreciated years ago. The correct parameter to use now is ignore_sticky_posts. Your query is also really inefficient and not good for performance.

Here is how I would tackle this issue

  • Use get_queried_object_id() to get the current post ID instead of the more unreliable method using the global $post

  • Use wp_get_post_terms() to return all the tag ID’s assigned to the post. From what I make, we only need to get ID’s, and not the complete tag objects

  • Use a proper tax_query to get all posts that have any of these tags attached to them. This is more personal preference as it is easy to change across taxonomies and also, looking at source code, the tag parameters use a tax_query

  • Use rand as value to the orderby parameter in WP_Query

In short, putting this all in code: (Untested, requires PHP 5.4+)

<?php
$tags = wp_get_post_terms( get_queried_object_id(), 'post_tag', ['fields' => 'ids'] );
$args = [
    'post__not_in'        => array( get_queried_object_id() ),
    'posts_per_page'      => 5,
    'ignore_sticky_posts' => 1,
    'orderby'             => 'rand',
    'tax_query' => [
        [
            'taxonomy' => 'post_tag',
            'terms'    => $tags
        ]
    ]
];
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
    echo '<div id="related"><h4>Related Posts</h4>';
        while( $my_query->have_posts() ) {
            $my_query->the_post(); ?>
            <div class="ncc">

                <h5><a href="https://wordpress.stackexchange.com/questions/183494/<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>" rel="nofollow"><?php the_title(); ?></a></h5>
                <?php the_excerpt(); ?>

            </div><!--ncc-->
        <?php }
        wp_reset_postdata();
    echo '</div><!--related-->';
}
?> 

Leave a Comment