Hiding toggle buttons when associated menus are empty

It might seem obvious, but many themes don’t do it (including mine, until very recently)!

Making sure buttons that toggle empty things are hidden is a quick win to improve theme user experience.

Why empty menus may be hard to miss

By default, the wp_nav_menu function falls back on wp_list_pages. That means, if a menu is not assigned to a location, it will still output a list of pages.

On a typical WordPress installation, one published page called “Sample Page” is preloaded. However, an empty menu could still exist in the following scenarios:

  • There are no published pages (“Sample Page” could be set as draft or trashed on a new installation).
  • An “empty menu” is assigned to the menu location.

Both plausible situations. Consider a minimalist website that has no need for a primary menu. Perhaps opting to use a less conspicuous menu location in the footer to link to their privacy policy, terms of service, etc.

Code examples

While you could use the has_nav_menu conditional function here, this would prevent the fallback from displaying, which could be confusing to users.

Users would have to manually create a menu and assign it to the location for a menu to show up, instead of having a probably-useful list of pages display automatically instead.

Therefore, hiding the menu toggles is best handled by JavaScript.

Pure JavaScript

If you’re using Underscores, hiding menu toggles for empty menus is already built in. Take a look at this code in navigation.js, for example:

// Hide menu toggle button if menu is empty and return early.
if ( 'undefined' === typeof menu ) {
	button.style.display = 'none';
	return;
}

If you’re rolling your own menu toggle functionality, then you want to make sure your code has similar handling.

jQuery

In the Spatial theme, I added this jQuery snippet to do something similar.

// Hide menu toggle button if menu is empty and return early
if ( ! jQuery( '#slide-out ul' ).length ) {
	jQuery( '.menu-toggle' ).hide();
	return;
}

You may need to adjust the #slide-out ul and .menu-toggle selectors to match your toggleable container and toggle button, respectively.

Request tutorials, download exclusive themes, and post on our community forums with a free membership.

Join for free

Error: Please enter a valid email address

Error: Invalid email

Error: Please enter your first name

Error: Please enter your last name

Error: Please enter a username

Error: Please enter a password

Error: Please confirm your password

Error: Password and password confirmation do not match