是的,我找到了这个问题的解决办法。您可以从检索的menu\\u items中检索子项的数量wp_get_nav_menu_items. 此函数用于检索一组包含“menu\\u item\\u parent”信息的post对象。
在Walker\\u Nav\\u菜单类的start\\u el函数中,您可以在$item->ID中尝试匹配。方法如下:
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[\'primary\'] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
$count = 0;
foreach( $menu_items as $menu_item ){
if( $menu_item->menu_item_parent == $item->ID ){
$count++;
}
}
然后在$count变量中得到子项的计数。以下是完整代码:
class Count\\u Post\\u Walker扩展Walker\\u Nav\\u菜单{
function start_el(&$output, $item, $depth, $args) {
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\\t", $depth ) : \'\';
$class_names = $value = \'\';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = \'menu-item-\' . $item->ID;
$class_names = join( \' \', apply_filters( \'nav_menu_css_class\', array_filter( $classes ), $item, $args ) );
$class_names = \' class="\' . esc_attr( $class_names ) . \'"\';
$id = apply_filters( \'nav_menu_item_id\', \'menu-item-\'. $item->ID, $item, $args );
$id = strlen( $id ) ? \' id="\' . esc_attr( $id ) . \'"\' : \'\';
$output .= $indent . \'<li\' . $id . $value . $class_names .\'>\';
$attributes = ! empty( $item->attr_title ) ? \' title="\' . esc_attr( $item->attr_title ) .\'"\' : \'\';
$attributes .= ! empty( $item->target ) ? \' target="\' . esc_attr( $item->target ) .\'"\' : \'\';
$attributes .= ! empty( $item->xfn ) ? \' rel="\' . esc_attr( $item->xfn ) .\'"\' : \'\';
$attributes .= ! empty( $item->url ) ? \' href="\' . esc_attr( $item->url ) .\'"\' : \'\';
/* Code to get children count */
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[\'primary\'] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
$count = 0;
foreach( $menu_items as $menu_item ){
if( $menu_item->menu_item_parent == $item->ID ){
$count++;
}
}
$item_output = $args->before;
$item_output .= \'<a\'. $attributes .\'>\';
$item_output .= $args->link_before . apply_filters( \'the_title\', $item->title, $item->ID ) . $args->link_after;
$item_output .= \'</a>\';
if( $count > 0 )
$item_output .= \'(\'.$count.\')\';
$item_output .= $args->after;
$output .= apply_filters( \'walker_nav_menu_start_el\', $item_output, $item, $depth, $args );
}
}