Programmatically Assign Menus To Theme Locations In WordPress

In this tutorial we are going to look at how we can programmatically set a menu to a menu location. In WordPress you assign a menu to a location by going to the menu page in the admin area and click on manage locations this will take you to the page /wp-admin/nav-menus.php?action=locations. From here you will see a list of all the locations assigned to your theme with a dropdown where you can choose what menu you want to assign to the location. An example of when you will need to programmatically set this is on a plugin activation you create a number of new menus based on user role and want to assign these to a menu location. First this will need to get a list of menu locations, get a list of menus and assign the menu ID to the location.

Get All Menu Locations

First we need to get a list of all the registered menu locations in your WordPress theme to do this we can use the get_theme_mod() function, passing in the parameter of nav_menu_locations.


$locations = get_theme_mod( 'nav_menu_locations' );

This returns an array of key value pairs for the locations, the key being the ID of the menu location and the value is the menu term ID that is used in this location, so to change the menu in this location we need to replace the value. ## Change Menu Assigned To Location

Once we get the menu locations we can then loop through these locations and get the menu that we want to add to the menu, all we have to do is assign the menu term ID to the location array. When we have changed the locations we then set these in the theme by using the function set_theme_mod() passing in the parameter of nav_menu_locations.


$locations = get_theme_mod( 'nav_menu_locations' );

if(!empty($locations)) { foreach($locations as $locationId => $menuValue) { switch($locationId) { case ' admin-menu-location': $menu = get_term_by('name', 'Admin Menu', 'nav_menu'); break; case 'author-menu-location': $menu = get_term_by('name', 'Author Menu', 'nav_menu'); break; case 'subscriber-menu-location': $menu = get_term_by('name', ' Default Menu', 'nav_menu'); break; } if(isset($menu)) { $locations[$locationId] = $menu->term_id; } } set_theme_mod(' nav_menu_locations', $locations); }

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring