如何显示分类页的sub-categories?

How to display sub-categories of a category page?

我有这段代码可以在 header 中显示菜单,但我想显示所选类别页面的 child 类别,而不是 parents 类别。

  <?php
               $categories = get_the_category();
                $category_id = $categories[0]->cat_ID;
                foreach ( $category_id as $navItem ) {
                    $class_names = $value = '';

                    $classes = empty( $navItem->classes ) ? array() : (array) $navItem->classes;
                    $classes[] = 'menu-item-' . $navItem->ID;

                    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $navItem ) );

                    if ( in_array( 'current-menu-item', $classes ) )
                        $class_names .= ' active';

                    $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

                    $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $navItem->ID, $navItem );
                    $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
                    echo '<li ' . $id . ' ' . $class_names . '><a href="'.$navItem->url.'" title="'.$navItem->title.'">'.$navItem->title.'</a></li>';
                }
                ?>

谢谢

好的,我进行了一些搜索,我能够解决这个问题

这是代码

   <?php
         if(is_category() && the_category_ID(false) != NULL)
        {
        $categories = get_categories(array("child_of" => the_category_ID(false), "hide_empty" => 0));


        foreach ($categories as $category)
                {

                    $class_names = $value = '';

                    $classes = (array) $navitem ='';
                    $classes[] = 'menu-item-' . $category->cat_ID;

                    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $category ) );

                    if ( in_array( 'current-menu-item', $classes ) )
                        $class_names .= ' active';

                    $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

                    $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $category->cat_ID, $category );
                    $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

                      echo '<li ' . $id . ' ' . $class_names . '><a href="'.get_bloginfo("url") .'/category/' .$category->slug.'" title="'.$category->cat_name.'">'.$category->cat_name.'</a></li>'; 
                      } 



                }
                ?>

希望对大家也有帮助

the_category_ID()

这个获取当前页面类别的 ID,我们使用 false 所以它不会打印 ID

然后在子类别或子类别中循环并获取它们的名称 + URL

的 slug