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

时间:2014-05-29 12:28:54

标签: php wordpress

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

$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;

2 个答案:

答案 0 :(得分:0)

您不是在这里收集所有条款,而是收集所有帖子。 '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>";
    }
}

如此使用:

tax_list($taxonomy, $term_id);

答案 1 :(得分:0)

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

<?php wp_reset_query(); ?>