如何获取相关帖子,其中至少3个标签应与wordpress

时间:2017-11-15 10:09:25

标签: wordpress

我希望得到类似(相关)的帖子,这些帖子应该匹配至少3个标签(所有帖子都有10个以上的标签)。这可能吗?如果是的话请帮助。我不知道。

1 个答案:

答案 0 :(得分:0)

<?php 
    $rTag = wp_get_post_tags($post->ID);
    foreach($rTag as $individual_tag) $tag_ids[] = $individual_tag->term_id;
        $related = get_posts( array( 
                'tax_query' => array(
                  array(
                    'taxonomy' => 'post_tag',
                    'field'    => 'term_id',
                    'terms'    => $tag_ids,
                  ),
                ),
                'numberposts' => -1,
                'post__not_in' => array($post->ID),
              ) ); 
?>
<section id="discover">
    <h2>Related posts</h2>
    <div class="singlepost">
        <?php  if( $related )  foreach( $related as $post ) {
      setup_postdata($post); 
                $tag_count = 0;
                $tag_min_match = 3;
                    foreach ( $tag_ids as $tag ) {
                        if ( has_tag( $tag ) && $tag_count < $tag_min_match ) {
                            $tag_count ++;
                        }
                    }
                if ($tag_count >= $tag_min_match) {
                    echo '<h4>'. get_the_title() .'</h4>';
                }
            }
        wp_reset_query(); ?>
    </div>
</section>