0

I'm trying to find a way to query posts on that have at least X tags in common with the current post. This example is close but I don't want to have to nominate which tags.

//List of tag slugs
$tags = array('SOMEHOW INCLUDE ALL TAGS');

$args = array(
    'tag_slug__in' => $tags
    //Add other arguments here
);

// This query contains posts with at least one matching tag
$tagged_posts = new WP_Query($args);

echo '<ul>';
while ( $tagged_posts->have_posts() ) : $tagged_posts->the_post();
   // Check each single post for up to 3 matching tags and output <li>
   $tag_count = 0;
   $tag_min_match = 2;
   foreach ( $tags as $tag ) {
      if ( has_tag( $tag ) && $tag_count < $tag_min_match ) {
         $tag_count ++;
      }
   }
   if ($tag_count == $tag_min_match) {
      //Echo list style here
      echo '<li><a href="'. get_permalink() .'" title="'. get_the_title() .'">'. get_the_title() .'</a></li>';
   }
endwhile;
wp_reset_query();
echo '</ul>';

Any help appreciated.

1
  • I'm assuming I have at least 3 tags in common
    – Pete
    Dec 19, 2017 at 10:33

1 Answer 1

2

Try this

<?php
//List of tag slugs
$tags = array();

$posttags = get_the_tags();
if ($posttags) {
  foreach($posttags as $tag) {
    $tags[] = $tag->term_id; 
  }
}

$args = array(
    'tag__in' => $tags
    //Add other arguments here
);

// This query contains posts with at least one matching tag
$tagged_posts = new WP_Query($args);

echo '<ul>';
while ( $tagged_posts->have_posts() ) : $tagged_posts->the_post();
   // Check each single post for up to 3 matching tags and output <li>
   $tag_count = 0;
   $tag_min_match = 2;
   foreach ( $tags as $tag ) {
      if ( has_tag( $tag ) && $tag_count < $tag_min_match ) {
         $tag_count ++;
      }
   }
   if ($tag_count >= $tag_min_match) {
      //Echo list style here
      echo '<li><a href="'. get_permalink() .'" title="'. get_the_title() .'">'. get_the_title() .'</a></li>';
   }
endwhile;
wp_reset_query();
echo '</ul>';

The code will fetch all the tags associated with the current post, search other posts with similar tags and return post if 2 or more tags are matched.

Hope this helps.

11
  • did the code work?
    – Sid
    Dec 19, 2017 at 10:24
  • If I make the tag threshold to '1' then it shows some posts, but if I make the threshold '2' is shows no posts.
    – Pete
    Dec 19, 2017 at 10:27
  • This is working fine on my side. Please make sure that you have 2 posts with 2 or more similar tags in the same post type.
    – Sid
    Dec 19, 2017 at 10:41
  • Yes I definitely have 2 posts with 2 or more similar tags in the same post type
    – Pete
    Dec 19, 2017 at 10:43
  • pastebin.com/hJkDqMej is my theme file. It starts on line 252
    – Pete
    Dec 19, 2017 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.