我正在尝试做两件事,但我不知道怎么做:
为子类别指定与父类别相同的类别(即父类别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;
?>
最合适的回答,由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;
?>
如果级别数未知,则可以实现类似于递归函数的逻辑