是否在菜单列表中为子类别赋予与父类别相同的类(父类别-Slug)?

时间:2012-10-19 作者:Cody

我正在尝试做两件事,但我不知道怎么做:

为子类别指定与父类别相同的类别(即父类别slug)

创建一个显示“我的类别”的菜单,当鼠标悬停家长类别时,子类别将显示为下拉项

目前,我正在使用此代码为我的类别生成类名,并创建我的菜单:

<?php
    $args = array(
        \'hide_empty\'               => 0
     );
       $categories = get_categories($args); 
    $menu = \'<ul class="nav">\';
    // iterate through your categories
    foreach($categories as $category) { 
        $menu .= \'<li class="\' . \'cat-item category-\' . $category->slug . \'">\' . \'<a href="\'.get_category_link($category->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . \'">\' . $category->cat_name . \'</a>\' . \'</li>\'   
    }  
    $menu .= \'<li class="menu-border">\' . \'</li>\' . \'</ul>\';
    echo $menu;  
      ?>

1 个回复
最合适的回答,由SO网友:Mridul Aggarwal 整理而成

如果只需要两个级别,可以使用parent 参数实例

<?php
$args = array(
    \'hide_empty\' => 0,
    \'parent\' => 0
);
$categories = get_categories($args); 
$menu = \'<ul class="nav">\';
// iterate through your categories
foreach($categories as $category) { 
    $menu .= \'<li class="\' . \'cat-item category-\' . $category->slug . \'">\' . \'<a href="\'.get_category_link($category->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . \'">\' . $category->cat_name . \'</a>\';
    $children = get_categories( array(\'parent\' => $category->term_id) );
    if($children && !empty($children)) {
        $menu .= \'<ul class="subnav">\';
        foreach ($children as $child) {
            $menu .= \'<li class="\' . \'cat-item category-\' . $category->slug . \'">\' . \'<a href="\'.get_category_link($child->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $child->name ) ) . \'">\' . $child->cat_name . \'</a></li>\';
        }
        $menu .= \'</ul>\';
    }
    echo \'</li>\';
}  
$menu .= \'<li class="menu-border">\' . \'</li>\' . \'</ul>\';
echo $menu;  
?>
如果级别数未知,则可以实现类似于递归函数的逻辑

结束

相关推荐

wp_list_categories pagination

我想知道我是否可以为wp\\U list\\U类别分页?我尝试了paginate\\u链接,但运气不好。还是有好的解决方法?非常感谢。<?php $orderby = \'name\'; $show_count = 0; $pad_counts = 0; $hierarchical = 1; $taxonomy = \'categories\'; $title = \'\'; $exclude = \