Skip to content

Instantly share code, notes, and snippets.

@dompl
Last active November 5, 2023 03:50
Show Gist options
  • Save dompl/7e3b7fa9f2de508cfa51c735bf46d937 to your computer and use it in GitHub Desktop.
Save dompl/7e3b7fa9f2de508cfa51c735bf46d937 to your computer and use it in GitHub Desktop.
Auto assign navigation after theme swith
<?php
/**
* Class NavigationAutoAssign
* Automatically assigns a navigation menu to a specified theme location in WordPress.
*/
class NavigationAutoAssign {
/**
* @var string The location identifier for the navigation menu within the theme.
*/
private $navLocationID;
/**
* @var string The name of the navigation menu to be assigned.
*/
private $navigationName;
/**
* Constructor for the NavigationAutoAssign class.
*
* @param string $navigationName The name of the navigation menu to assign.
* @param string $navLocationID The theme location ID where the menu should be assigned.
* Default is set to 'header'.
*/
public function __construct($navigationName, $navLocationID = 'header') {
$this->navigationName = $navigationName;
$this->navLocationID = $navLocationID;
// Adds a callback function to the 'after_setup_theme' hook.
add_action('after_setup_theme', [$this, 'assignMenuToLocation']);
}
/**
* Assigns the navigation menu to the specified location.
* This method is intended to be hooked into 'after_setup_theme' action.
*/
public function assignMenuToLocation() {
// Retrieve the menu object by menu name.
$menu = get_term_by('name', $this->navigationName, 'nav_menu');
if (!$menu) {
// If the menu does not exist, log an error and return early.
error_log('Menu not found: ' . $this->navigationName);
return;
}
$menu_id = $menu->term_id;
// Retrieve the current menu locations.
$locations = get_theme_mod('nav_menu_locations');
// Check if the menu is already assigned to the specified location to avoid unnecessary operations.
if (isset($locations[$this->navLocationID]) && $locations[$this->navLocationID] === $menu_id) {
// The menu is already assigned to the location, so no further action is needed.
return;
}
// Assign the retrieved menu to the specified location.
$locations[$this->navLocationID] = $menu_id;
// Save the modified locations back to the theme.
set_theme_mod('nav_menu_locations', $locations);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment