I know how to add a Walker to a custom menu created by the theme (menu named primary
in this example), but how can I target a menu thats created in a widget with the default wordpress custom menu widget?
if ( has_nav_menu( 'primary' ) ) {
$args = array(
'menu' => 'main-menu',
'menu_id' => 'main-menu',
'theme_location' => 'primary',
'depth' => 0,
'container' => false,
'menu_class' => 'nav',
'walker' => new Myprefix_Walker_Nav_Menu(),
'echo' => 0
);
$nav = wp_nav_menu( $args );
}
If you look at implementation of
WP_Nav_Menu_Widget
class you will see the following code:It means that there is no any chance to hook a menu. So you need to take a look at
wp_nav_menu
function implementation, where you can find following lines of code:Here you can see that all arguments passed to the
wp_nav_menu
function could be replaced. So what you need is to create your own hook handler which will add your walker to a navigation menu. It could be simple as:Expanding on @Eugene’s answer, if you want to limit this to a specific menu, just check the term ID of the menu:
This is an alternative to targeting a menu by
term_id
and I thought it might be of use to someone as a way of modifying several menus without having to look up their ids.By adding
print_r($args)
to a filter, I noticed that$args['menu']
is a string for menus in predefined theme locations andWP_Term_Object
for a custom menu widget in a sidebar.I used this to target menus by slug and add a class to their container. A number of menus can be targeted by including a common string in their slugs. Note: menu slug comes from the array key in
register_nav_menus()
.For a single menu you would just need to check that
$args['menu']->{slug} == 'your-slug'
instead of the strpos() bit above.You can add a custom walker to a nav menu created in a widget using the
widget_nav_menu_args
filter added in wordpress4.2.0
. It accepts four arguments (seewp-includes/widgets/class-wp-nav-menu-widget.php
). But to add only a custom walker you just need to use the first argument, the same way you use thewp_nav_menu_args
filter.