Themetry is no longer operational. This site is here for archival purposes. See what Leland is working on at le.land.

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.

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.

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:

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

jQuery

In the Spatial theme, the author added this jQuery snippet:

// 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 selectors to match your toggleable container and toggle button, respectively.

Previous Post
Cropping images with nothing but CSS
Next Post
Diagnosing high CPU load complaints from your web host