Counting top level items in menu
-
Hi everyone,
I’m creating options in my theme customizer based on number of top level items in currently active menu. I want to create options dynamically, and exclude submenu items from creating options, only options for top level menu items should be created.
This is the code I wrote:$dc_get_menu = wp_get_nav_menu_items('Main menu'); $counter = 0; foreach($dc_get_menu as $key => $menu_item) { if ($menu_item->menu_item_parent != 0 ) continue; $counter++; $wp_customize->add_setting( 'dc_menu_icon_' . $counter, array( 'default' => ' ' ) ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'dc_menu_icon_' . $counter, array( 'label' => 'Menu icon ' . $counter, 'section' => 'divi_center_menu_icons', 'settings' => 'dc_menu_icon_' . $counter, ) ) ); }
It is actually working. But my questions is I have this part here:
if ($menu_item->menu_item_parent != 0 )
I used if from other stackoveflow code snippet and implemented here. As can be seen on reference page here:
menu_item_parent: The DB ID of the nav_menu_item that is this item’s menu parent, if any. 0 otherwise.
By definition, here if menu item doesn’t have parent 0 should be returned. However when I use to check if ID is 0, I get submenu items counted. And when I use to check if not 0, I got only top level menu items.
I like to understand my code, even if I somehow made it working, but this is situation where I don’t completely understand why is it working, and even more important is this the best way to do it, and would appreciate if you provide explanation for it.
Thank you! ??
- The topic ‘Counting top level items in menu’ is closed to new replies.