Custom Walker navigation menus for header and footer
Problem: Very often we have different menus structure for header and footer. How to we check and set menu in depending their locations?

Solution: One of solutions is is pass as an argument of the object is a menu location. So, let's do simple few steps:
Step 1: Register menu (functions.php):
<?php
...
// Register Nav Menus
register_nav_menus( [
'primary' => __( 'Primary Navigation', 'theme_name' ),
'secondary' => __( 'Footer Navigation', 'theme_name' ),
] );
...
Step 2: Call menu at the right place e.g. in the header.php
<?php
...
if ( has_nav_menu( 'primary' ) ) {
wp_nav_menu( [
'container' => false,
'theme_location' => 'primary',
'menu_id' => 'nav',
'menu_class' => 'nav navbar-nav',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'walker' => new Custom_Walker_Nav_Menu('primary'),
]);
}
...
Step 3: In the Walker class use some like this:
<?php
// Custom Menu Walker
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu
{
public $menu_location = 'primary';
function __construct( $menu_location_var ) {
$this->menu_location = $menu_location_var;
}
...
function start_el( &$output, $item, $depth = 0, $args = [], $id = 0 ) {
...
// Way 1, if we need menu object
$locations = get_nav_menu_locations(); // get all menu locations
$menu = wp_get_nav_menu_object( $locations[ $this->menu_location ] );
...
// Way 2, if we need only location
$menu_location = $this->menu_location;
...
}
}
Source:
Awesome thіngs here. I’m vеry happy to peer yoᥙr article.
Thanks so much and I’m looking aheaⅾ to contact you.
Will yօu please drop me a e-mail?
For contact me you can use Contact Form at the right bottom part at everything the site’s pages.