Show related posts by term value

Here’s another quick tip. I needed to create a simple WordPress query that would find related posts tagged with the same term as the current post.

Also, I needed to make sure it wouldn’t include the current post in the return. This worked for me, but feel free to offer suggestions that can make this better.

<?php
global $post;
$terms = get_the_terms( $post->ID , 'taxonomy_slug_goes_here', 'string');  // Insert the slug of the taxonomy in which you would like to check for related terms
$current_post[] = $post->ID;
 
if(!empty($terms)){
    foreach ($terms as $term) {
        query_posts( array(
        'taxonomy_slug_goes_here' => $term->slug,  // Insert the slug of the taxonomy in which you would like to check for related terms
        'showposts' => 3,  // Set how many posts you would like to return
        'caller_get_posts' => 1,
        'post__not_in' => $current_post ) );  // Makes sure to not include the current post
        if(have_posts()){
            while ( have_posts() ) : the_post(); $current_post[] = $post->ID; ?>
            Related post content goes here
            <?php endwhile; wp_reset_query();
        }
    }
}
?>