显示子类别而不是父类别

时间:2016-07-21 03:59:23

标签: wordpress categories

我使用下面的代码显示WordPress帖子类别,但它输出父类别,而不是子类别。可以修改它以显示子类别吗?

00
01
10
11
0B
B0
B1
1B
BB

2 个答案:

答案 0 :(得分:0)

使用此代码按ID

获取子类别
    <?php $cats = get_the_category($post->ID);
$sep = '';
foreach( $cats as $cat ) {
  $subcats = get_categories('child_of='.$cat->term_id);
  if($subcats) {
    foreach( $subcats as $subcat )
      {   echo $sep . $subcat->name; $sep = ', '; }
  }
}
?>

答案 1 :(得分:0)

如果要显示WordPress类别列表,请使用此代码

 <div class="category"> <?php _e('Categories:'); ?> <?php wp_list_cats(); ?></div>

或者您想调用woocomerce类别然后调用使用此代码

 <div class="category">
        <?php

          $taxonomy     = 'product_cat';
          $orderby      = 'name';  
          $show_count   = 0;      // 1 for yes, 0 for no
          $pad_counts   = 0;      // 1 for yes, 0 for no
          $hierarchical = 1;      // 1 for yes, 0 for no  
          $title        = '';  
          $empty        = 0;

          $args = array(
                 'taxonomy'     => $taxonomy,
                 'orderby'      => $orderby,
                 'show_count'   => $show_count,
                 'pad_counts'   => $pad_counts,
                 'hierarchical' => $hierarchical,
                 'title_li'     => $title,
                 'hide_empty'   => $empty
          );
         $all_categories = get_categories( $args );
         foreach ($all_categories as $cat) {
            if($cat->category_parent == 0) {
                $category_id = $cat->term_id;       
                echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';

                $args2 = array(
                        'taxonomy'     => $taxonomy,
                        'child_of'     => 0,
                        'parent'       => $category_id,
                        'orderby'      => $orderby,
                        'show_count'   => $show_count,
                        'pad_counts'   => $pad_counts,
                        'hierarchical' => $hierarchical,
                        'title_li'     => $title,
                        'hide_empty'   => $empty
                );
                $sub_cats = get_categories( $args2 );
                if($sub_cats) {
                    foreach($sub_cats as $sub_category) {
                        echo  $sub_category->name ;
                    }   
                }
            }       
        }
        ?>
    </div>