如果有多个帖子,WordPress自定义分类法术语重复


WordPress custom taxonomy term repeats if have more than one post

我在侧边栏上有术语链接当我附加多个帖子到术语时,它会重复。

$args = new WP_Query(array('post_type' => 'song', 'post_status' => 'publish', 'posts_per_page' => '-1'));
        while ($args->have_posts()) : $args->the_post();
        $terms = get_the_terms( $post->ID, 'song-categories' );
        if ($terms && ! is_wp_error($terms)){ 
          foreach($terms as $term) { 
          if ($term_id ==  $term->term_id){ $curent_term = ' class="current"'; } else {$curent_term = '';}
            echo '<li><a href="'.get_term_link($term->slug, 'song-categories').'" class="'.$term->slug.'">'.$term->name.'</a></li>';
          }
        } 
    endwhile;

这里收集的不是所有的术语,而是所有的帖子。'posts_per_page' => '-1'

$args = new WP_Query(array('post_type' => 'song', 'post_status' => 'publish', 'posts_per_page' => '-1'));
    while ($args->have_posts()) : $args->the_post();

因此,对于每个帖子,您将获得所有条款:

$terms = get_the_terms( $post->ID, 'song-categories' );

你需要使用不同的方法。在过去,我用过这样的句子:

function tax_list($tax, $current = null){
    $terms = get_terms( $tax, 'orderby=count&hide_empty=1' );
    foreach($terms as $term){
        if($current == $term->term_id){
            $class= " class='active'";
        }else{
            $class= "";
        }
        $name = $term->name;
        $link = get_term_link( $term->slug, $tax );
        echo "<li><a href='$link'$class>$name</a></li>";
    }
}

用作so:

tax_list($taxonomy, $term_id);

在使用自定义查询前重置您的查询

<?php wp_reset_query(); ?>