0

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.

0

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++;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.