查询至少具有当前帖子的3个标签的帖子

时间:2017-12-19 作者:Pete

我试图找到一种方法来查询与当前帖子至少有X个相同标签的帖子。This example 很接近,但我不想指定哪个标签。

//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>\';
感谢您的帮助。

1 个回复
SO网友:Sid

试试这个

<?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>\';
代码将获取与当前帖子相关的所有标签,搜索具有类似标签的其他帖子,如果有2个或更多标签匹配,则返回帖子。

希望这有帮助。

结束

相关推荐

Set post tags using tag ID

我想将post标记设置为新值。有没有办法使用tag ID 这样做?这个wp_set_post_tags 仅接受tag name 或array of tag names.<?php wp_set_post_tags( $post_ID, $tags, $append ) ?> 我想使用ID 我不想为获取完整的标记对象进行额外调用。