WordPress Querying Related Posts by tag

I am trying to query a list of posts with the same tags as the current post being viewed in WordPress. I thought that if I could query the list of tags for the current post, pass it into a variable and then pass that variable into query_posts argument it would get the job done. It seems to work for one of the tags in the post but I am clearly doing something wrong. Here is a sample of the code I have written thus far:

<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
    $test = ',' . $tag->name; 
}
}
query_posts('tag=' .$test . '&showposts=-1'); while (have_posts()) : the_post(); ?>
      <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<?php endwhile; wp_reset_query(); ?>

Any clarification on what I’m doing wrong would be very much appreciated.

Related posts

Leave a Reply

2 comments

  1. You’re resetting $test everytime.

    Try

    <?php
    $test = "";
    $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
        $test .= ',' . $tag->name; 
    }
    }
    $test = substr($test, 1); // remove first comma
    query_posts('tag=' .$test . '&showposts=-1'); while (have_posts()) : the_post(); ?>
          <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
    <?php endwhile; wp_reset_query(); ?>
    
  2. You need to accumulate the tags into the test variable,

    <?php
    $posttags = get_the_tags();
    $test = '';
    $sep = '';
    if ($posttags) {
        foreach($posttags as $tag) {
            $test .= $sep . $tag->name; 
            $sep = ",";
        }
    }
    query_posts('tag=' .$test . '&showposts=-1'); while (have_posts()) : the_post(); ?>
    <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
    <?php endwhile; wp_reset_query(); ?>