首页 > 解决方案 > 排除未分配帖子的 wp 类别

问题描述

我有一个自定义帖子类型“顾问”和自定义分类“顾问类别”。我需要输出所有已分配帖子的自定义分类法(类别)。但是上面的代码输出所有分类法,包括那些没有分配帖子的分类法 - 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>

标签: phpwordpresscustom-taxonomytaxonomy-terms

解决方案


你试过添加

'hide_empty' => true,

获取条款?

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

推荐阅读