Filter and Hooks, Programming, WordPress

WordPress: Get Menu Items and it’s sub-items in an array

WordPress provides built in function that displays the navigation menus without having trouble to write any code. But, in some cases we may want an arrays of menu items and tweak it.

Following steps are handy for grouping the menu items in  a single array.

1. Register your custom navigation menu.
We have readily available function to register our custom menu, therefore we do not need to call add_theme_support( ‘menus’ ) :

register_nav_menus( $locations );

Here, $locations is an associative array of menu location slugs (key) and descriptions (according value). I have registered custom menu ‘primary_menu’ as a key  and ‘Main menu’ is the description for the registered ‘primary_menu’

add_action( 'after_setup_theme', 'register_custom_nav_menu' );
function register_custom_nav_menus() {
 register_nav_menu( 'primary_menu', __( 'Main Menu', 'app' ) );
}

 

2. Create and add Menu items the dashboard

 

3. Get the array of Menu items

Use the custom menu key ‘primary_menu’ in my case to get the  all the menu items associated with it.

$menu_name = 'primary_menu';
$locations = get_nav_menu_locations();
//Get the id of 'primary_menu'
$menu_id = $locations[ $menu_name ] ;
//Returns a navigation menu object.
$menuObject = wp_get_nav_menu_object($menu_id);
// Retrieves all menu items of a navigation menu.
$current_menu = $menuObject->slug
$array_menu = wp_get_nav_menu_items($current_menu);

4. Function to the get the array of menu items

You can create your own function to get the menu items and its sub-items in an array

function wp_get_menu_array($current_menu) {

                    $array_menu = wp_get_nav_menu_items($current_menu);
                    $menu = array();
                    foreach ($array_menu as $m) {
                        if (empty($m->menu_item_parent)) {
                            $menu[$m->ID] = array();
                            $menu[$m->ID]['ID']      =   $m->ID;
                            $menu[$m->ID]['title']       =   $m->title;
                            $menu[$m->ID]['url']         =   $m->url;
                            $menu[$m->ID]['children']    =   array();
                        }
                    }
                    $submenu = array();
                    foreach ($array_menu as $m) {
                        if ($m->menu_item_parent) {
                        $submenu[$m->ID] = array();
                            $submenu[$m->ID]['ID']       =   $m->ID;
                            $submenu[$m->ID]['title']    =   $m->title;
                            $submenu[$m->ID]['url']  =   $m->url;
                           $menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
                        }
                    }
                    return $menu;

                }

 

Views: 3694

Standard