Display the children of a WordPress menu item

Since the days of using Joomla, I’ve been after a convenient way of displaying ONLY the second level of a WordPress menu, or the children of an active menu, without displaying the parent level items.

Finally! here is a solution that helps you do just that.

Finally display level 2 menu items in WordPress
Woman Happy about this new WordPress menu!

We normally do not advise the installation of too many WordPress plugins but to perform this task. The installation of the following plugin is required, we have tried and tested this plugin on a number of different websites and had some great results.

Please install the following Plugin:

Once the plugin is installed you will now need a way to display the menu or the words that actually appear in the menu item itself. The wp_nav_menu plugin uses words like “Home” “About us” “Contact us” or the menu ID’s to display its child content.

Get WordPress Menu ID of the current active menu

The following code is required to be placed in the functions.php file. This will allow the current menu ID’s to be displayed when a variable (wpse16243_wp_nav_menu_objects) is called.

//assign menu id to $GLOBALS['wpse16243_title'] to query in subsite-menu.php 
add_filter( 'wp_nav_menu_objects', 'wpse16243_wp_nav_menu_objects' );
function wpse16243_wp_nav_menu_objects( $sorted_menu_items )
{
    foreach ( $sorted_menu_items as $menu_item ) {

        if ( $menu_item->current ) {

            if(!in_array('menu-item-has-children',  $menu_item->classes)&&$menu_item->menu_item_parent!=0){
                $GLOBALS['wpse16243_title'] = $menu_item->menu_item_parent;
            }else{
              $GLOBALS['wpse16243_title'] = $menu_item->ID;
            }

            break;
        }
    }
    return $sorted_menu_items;
}

Now that we have the title displayed in a GLOBAL object we can call it back to the display that is required in the wp_nav_menu plugin.

Use the following code to display the second menu item.

$default_menu_level_two = array(
    'menu' => 'main',
    'level' => 2,
    'child_of' => (int)$GLOBALS['wpse16243_title'],
    'container'       => '',
    'container_class' => '',
    'menu_class'      => 'sub-menu hidden-xs',
    'echo' => FALSE,
);
$sub_menu = wp_nav_menu( $default_menu_level_two );
echo $sub_menu;

This works well for the most part, but we later identified 1 problem. The sub-menu was displaying when the title was returning a “0” Zero int value and when the $sub_menu value was empty so we used a simple IF statement to bypass both these variables.

The following is the additional bit of code to be added to check the variables before the $sub_menu is finally echoed.

if ( !empty ( $sub_menu ) && $GLOBALS['wpse16243_title'] != 0 ){
  echo $sub_menu;
}

Please let us know in the comments below if you have a better / simpler approach to displaying sub-menu items in WordPress.

Comments

Join the discussion!