Customize Navigation Menu widgets in sidebars

The Navigation Menu widget allows you to display a custom menu on a registered sidebar… The widget is not customizable as it does not provide any options, fortunately, there’s a hook for that.

The Navigation Menu widget does not provide any options.

The widget outputs the menu using the standard wp_nav_menu() function and passes its arguments through the widget_nav_menu_args filter. Using this filter you may modify things like the menu_class, menu_id, link_before, link_after and even pass a custom walker class.

Modifying these arguments would affect all the Navigation Menu widgets, however, it is possible to target a specific menu by checking values in the $nav_menu and $args arguments passed in the widget_nav_menu_args hook.

The example below shows how to specifically target the menu with the slug ‘social’ located in the sidebar with id ‘sidebar-1‘.

add_filter('widget_nav_menu_args', function ($nav_menu_args, $nav_menu, $args, $instance) {

	if ($args['id'] == 'sidebar-1' && $nav_menu->slug == 'social') {
		$nav_menu_args['menu_class']  = "my-menu-class";
		$nav_menu_args['menu_id']     = "my-menu-id";
		$nav_menu_args['link_before'] = '<span class="screen-reader-text">';
		$nav_menu_args['link_after']  = '</span>';
	}

	return $nav_menu_args;

}, 10, 4);

You could also target all menus in a particular sidebar or a specific menu located in any sidebar.

add_filter('widget_nav_menu_args', function ($nav_menu_args, $nav_menu, $args, $instance) {

	/**
	 * Change the menu class to 'nav' on all menus in sidebar-1
	 */

	if ($args['id'] == 'sidebar-1') {
		$nav_menu_args['menu_class'] = "nav";
	}

	/**
	 * Wrap link text in a span on all menus with slug social
	 */

	if ($nav_menu->slug == 'social') {
		$nav_menu_args['link_before'] = '<span class="screen-reader-text">';
		$nav_menu_args['link_after']  = '</span>';
	}

	return $nav_menu_args;

}, 10, 4);

Recent Articles