Skip to main content

Different CSS class for wp_nav_menu in the menu widget

When playing with the awesome theme Responsive I notice the menu in widget was broken because it was styling on the CSS class ‘menu’. Since every menu has this class the widgets also get the main menu styling. You can fix this in the child theme by removing all styling but that seems hard to day. And fixing this in the theme itself can be hard. Changing the selectors can mean you are overwriting styles from a child theme. Doesn’t have to but it can happen.

So I looked at the WordPress code and see if there was a way to change that when the function wp_nav_menu() is used inside a widget. I found out that this is something you can’t do since dynamic_sidebar() doesn’t have a begin and an end hook. I did notice that every widget before it’s going to be displayed fires the filter ‘widget_display_callback’. So I hooked to that and check what kind of widget we are dealing with since we need the widget to stop using the filter and we do need a wp_nav_menu() for that. When this code is in place then we just can use the filter inside wp_nav_menu() to change the class name. What is pretty awesome to do in cases like this and maybe WordPress should do this by default.

Currently the class is very static because of the hardcoded instanceof check. Most likely you can work around by putting all possible widgets classes in an array, using apply_filters on that array, get_class( $widget ) and do an in_array().

public function menu_different_class( $settings, $widget ) {
	$widget_class = get_class( $widget );
	$classes      = apply_filters( 'nav_menu_widget_widgets', array( 'WP_Nav_Menu_Widget' ) );

	if( in_array( $widget_class, $classes ) )
		add_filter( 'wp_nav_menu_args', array( $this, 'wp_nav_menu_args' ) );

	return $settings;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.