Custom Nav Walker menu – Display children count

I sort of added onto @Giri’s answer by using array_map and array_count_values. if this helps anyone in the future. I didn’t wish to use a counter and a foreach loop for something so simple.

function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
    if ($item->hasChildren) {
        $locations = get_nav_menu_locations(); // Getting the locations of the nav menus array.
        $menu = wp_get_nav_menu_object( $locations['primary_navigation'] ); // Getting the menu calling the walker from the array.
        $menu_items = wp_get_nav_menu_items($menu->term_id); // Getting the menu item objects array from the menu.
        $menu_item_parents = array_map(function($o) { return $o->menu_item_parent; }, $menu_items); // Getting the parent ids by looping through the menu item objects array. This will give an array of parent ids and the number of their children.
        $children_count = array_count_values($menu_item_parents)[$item->ID]; // Get number of children menu item has.
    }
}

Leave a Comment