排除没有分配帖子的 wp 类别

问题描述

我有一个自定义帖子类型“顾问”和自定义分类“consultants_category”。我需要输出分配了帖子的所有自定义分类法(类别)。但是上面的代码输出所有分类法,包括那些没有分配帖子的分类法 - https://prnt.sc/zr96jh 请帮助我改进此代码。 谢谢。

    <div class="cp_allconsultants-l1_list_new">
        <?PHP
            $terms = get_terms(array(
                        'term' => 'consultants_category',));
            foreach( $terms as $term ):
            ?>    
            <div class="l2posts_by_cat">                      
                <h3><?PHP echo $term->name; ?></h3>                          
                <ul>
                  <?PHP                         
                      $posts = get_posts(array(
                        'post_type' => 'consultants','taxonomy' => $term->taxonomy,'term' => $term->slug,'nopaging' => true,));
                      foreach($posts as $post): 
                        setup_postdata($post); 
                  ?>        
                      <li><a href="<?PHP the_permalink(); ?>"><?PHP the_title(); ?></a></li>    
                    <?PHP endforeach; ?>
                </ul>
            </div>                                                       
        <?PHP endforeach; ?>
    </div>

解决方法

您是否尝试添加

'hide_empty' => true,

到get_terms?

$terms = get_terms(array(
    'term' => 'consultants_category','hide_empty' => true,));