如何显示类别页面的子类别?

时间:2020-03-26 16:38:01

标签: wordpress-theming menuitem

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

  <?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>';
                }
                ?>

谢谢

1 个答案:

答案 0 :(得分:0)

好吧,我进行了一些搜索,然后就可以解决这个问题

这是代码

   <?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

然后循环进入子类别或子类别,并获取其名称+网址的子弹