How to add menu-slug-container class when setting a custom one in wp_nav_menu’s container_class

Posted on

In my last tutorial I wanted to output a nav menu assigned to a particular theme location with the nav element having the standard auto generated class as well as a custom one.

wp_nav_menu(
	array(
		'theme_location' => 'header',
		'divider_html' => $divider_html,
		'container' => 'nav',
		'menu_class' => 'menu genesis-nav-menu menu-header js-superfish'
	)
);

If we want to add a custom nav-header class to the nav element, changing the code to

wp_nav_menu(
	array(
		'theme_location' => 'header',
		'divider_html' => $divider_html,
		'container' => 'nav',
		'container_class' => 'nav-header',
		'menu_class' => 'genesis-nav-menu menu-header js-superfish'
	)
);

Here’s how it can be done:

$location_name = 'header';
$locations = get_nav_menu_locations();
$menu_id = $locations[ $location_name ];
$menu = wp_get_nav_menu_object( $menu_id );

wp_nav_menu(
	array(
		'theme_location' => 'header',
		'divider_html' => $divider_html,
		'container' => 'nav',
		'container_class' => 'menu-'. $menu->slug .'-container' . ' nav-header',
		'menu_class' => 'genesis-nav-menu menu-header js-superfish'
	)
);

where header is the name of my desired menu theme location.