Skip to content

Snippet: How to Change The Main Menu Location Conditionally

In the Total theme the main header menu by default uses the "main_menu" location. However, you can easily alter the default location using the "wpex_main_menu_location" filter. This can be useful if you want to define a new menu location via the wp_register_nav_menu function and conditionally display it in your header. Below is an example snippet. However, if what you want to do is alter the main_menu menu ID you can do so as well but you would want to instead use the "totaltheme/header/menu/wp_menu" filter.

// Define new menu location for WooCommerce pages
add_action( 'after_setup_theme', function() {
	register_nav_menu( 'woocommerce', __( 'WooCommerce Menu', 'total' ) );
} );

// Alter Main Menu Location Via Hook
add_filter( 'totaltheme/header/menu/theme_location', function( $location ) {
	
	// Display "woocommerce" menu location for woocommerce pages
	if ( function_exists( 'is_woocommerce' ) && is_woocommerce() ) {
		return 'woocommerce';
	}

	// Return location
	return $location;

} );
All PHP snippets should be added via child theme's functions.php file or via a plugin. We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top