Creating a Custom Menu for Mobile

In this tutorial, I’ll share how to create a custom menu for mobile devices. This way, you can manage two separate menus within your WordPress admin, one for desktop and one for mobile devices.

mobile-menu

For the mobile user, we generally don’t want to limit the content that can be accessed, but instead present it in a way that is easy to use and read from smaller devices. This is general idea behind responsive design, where we create a design for our content that can be presented for any viewport size. So, within our themes, this is why by default we assume you’re going to have a shared primary navigation across your entire website, no matter what device is displaying it.

With that said, as we dive deeper into a project, we sometimes realize not everything works in the most ideal of ways, and we need to adapt. In the support forums, there have been several instances over the years where people want to create a custom menu for mobile, for a myriad of reasons.

Here’s how you’d set it up from your child theme’s functions.php:

/**
 * Register new theme menu location, to be used
 * for mobile devices.
 */
function my_register_menus() {
	register_nav_menu('mobile', 'Mobile Menu');
}
add_action('after_setup_theme', 'my_register_menus');

/**
 * Filter in the menu location registered
 * for mobile.
 */
function my_primary_menu_location( $menu ) {

	if ( wp_is_mobile() ) {
		$menu = 'mobile';
	}

	return $menu;
}
add_filter('themeblvd_primary_menu_location', 'my_primary_menu_location');

Important! Because we’re using wp_is_mobile() to actually apply the menu location on the frontend, this means that it’s not applied in the same “responsive” way you might be used to based on the viewport sizing alone. We’re using PHP to determine, not if the viewport is of certain dimensions, but if the physical device is an actual mobile device.

In other words, if you’re on a desktop computer, and you scale the web browser down to a mobile viewport size, you’re not going to see your mobile menu; instead, you need to actually view your site on a mobile device, like an iPhone, iPad, etc.