How to use different Walker menus for header and footer?

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:

  1. https://wordpress.stackexchange.com/questions/256868/walker-nav-menu-put-custom-code-between-a-particular-li