Get Current Menu Location inside Nav_Walker
-
17-04-2021 - |
Question
How can I retrieve the current menu location (as registered with register_nav_menus
) from inside a nav-walker class?
eg:
<?php
class Special_Nav_Walker extends Walker_Nav_Menu {
// How can I get `special_menu` here, when the walker is applied to the menu (see below)
}
wp_nav_menu(
[
'theme_location' => 'special_menu',
'walker' => new Special_Nav_Walker(),
]
);
Solution
There's no constructor, so it's not available as a property of the class, but each method in the class receives the arguments passed to wp_nav_menu()
as an object. For example, start_lvl()
:
/**
* Starts the list before the elements are added.
*
* @since 3.0.0
*
* @see Walker::start_lvl()
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args An object of wp_nav_menu() arguments.
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
if ( 'special_menu' === $args->theme_location ) {
// Do something.
}
}
Yes, the default value for $args
is an array, but nav walkers receives it as an object, for some reason.
The other methods also make the arguments available, but not necessarily as the 3rd argument. You'll need to see which parameters are passed to each method, but you need to do that when extending a class anyway.
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange