When you filter wp_nav_menu
, you get the nav menu arguments as second parameter $args
. That’s an object (a stdClass
), set by WordPress while figuring out which menu to use, with an entry named menu
. This is the whole nav menu object. Its title is in the entry name
.
Here is a trick: you can pass custom arguments to wp_nav_menu()
.
Let’s say you are calling wp_nav_menu()
like this:
wp_nav_menu(
[
'theme_location' => 'secondary',
'container' => 'div',
'container_class' => 'submenu-container sub-menu clearfix',
'menu_class' => 'ipf-sectionmenu',
'heading' => '<h3 id="left-subheader-mobile" class="purple-header">%s</h3>',
]
);
Now you have the HTML for the heading in the arguments, and it is available together with the actual menu title on the hook wp_nav_menu
. All you have to do is bringing it together.
Dead simple, just add this to your functions.php
:
add_filter( 'wp_nav_menu', function( $nav_menu, $args ) {
if ( empty ( $args->heading ) )
return $nav_menu;
$title = esc_html( $args->menu->name );
$heading = sprintf( $args->heading, $title );
return $heading . $nav_menu;
}, 10, 2 );