php - Count top level menu items

admin2025-06-06  8

I need to get count of top level menu items.

I have menu with 5 items and of of them has 1 submenu. This is current situation, but the user using the theme I am building may have some different number. I am creating options in theme customizer and I need to create option for every item.

I tried using code like this:

    $menu_object = wp_get_nav_menu_object("Main menu");
    $menu_items_count = $menu_object->count;

    for($x = 1; $x <= $menu_items_count; $x++){
        $wp_customize->add_setting( 'menu_icon_' . $x, array( 
            'default' => ' '
         ) );
        $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'menu_icon_' . $x, array(
            'label' => 'Menu icon' . $x,
            'section' => 'menu_icons',
            'settings' => 'menu_icon_' . $x,
        ) ) );
    }

But here I'm creating 6 options instead of 5, because here $menu_object->count; counts submenu also.

I need to get count of top level menu items.

I have menu with 5 items and of of them has 1 submenu. This is current situation, but the user using the theme I am building may have some different number. I am creating options in theme customizer and I need to create option for every item.

I tried using code like this:

    $menu_object = wp_get_nav_menu_object("Main menu");
    $menu_items_count = $menu_object->count;

    for($x = 1; $x <= $menu_items_count; $x++){
        $wp_customize->add_setting( 'menu_icon_' . $x, array( 
            'default' => ' '
         ) );
        $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'menu_icon_' . $x, array(
            'label' => 'Menu icon' . $x,
            'section' => 'menu_icons',
            'settings' => 'menu_icon_' . $x,
        ) ) );
    }

But here I'm creating 6 options instead of 5, because here $menu_object->count; counts submenu also.

Share Improve this question asked Nov 12, 2018 at 0:13 UsceUsce 4671 gold badge4 silver badges20 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

I am not really sure whether there is some native function for this or not, but you could do it like this:

$menu_object = wp_get_nav_menu_object("Main menu");
$menu_items = wp_get_nav_menu_items($menu_object->term_id);
$menu_items_count = 0;

foreach ( (array) $menu_items as $key => $menu_item ) {
    if ($menu_item->menu_item_parent == 0 ) $menu_items_count++;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749191027a317125.html

最新回复(0)