I am attempting to add a data attribute to all menu items, but it’s simply not working. I am using wp_nav_menu
to call my menu walker as well.
function menu_anchor_attributes ( $atts, $item, $args ) {
$atts['data-menuanchor'] = $item->attr_title;
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'menu_anchor_attributes', 10, 3 );
I am using JointsWP as my framework, which includes this walker:
// The Top Menu
function joints_top_nav() {
wp_nav_menu(array(
'container' => false, // Remove nav container
'menu_class' => 'horizontal menu', // Adding custom nav class
'items_wrap' => '<ul id="%1$s" class="%2$s" data-responsive-menu="accordion medium-dropdown">%3$s</ul>',
'theme_location' => 'main-nav', // Where it's located in the theme
'depth' => 5, // Limit the depth of the nav
'fallback_cb' => false, // Fallback function (see below)
'walker' => new Topbar_Menu_Walker()
));
}
// Big thanks to Brett Mason (https://github.com/brettsmason) for the awesome walker
class Topbar_Menu_Walker extends Walker_Nav_Menu {
function start_lvl(&$output, $depth = 0, $args = Array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"menu\">\n";
}
}
2 Answers
Whenever an attribute is empty WordPress filters decide just not to show the attribute so a simple test for this is the following:
function menu_anchor_attributes ( $atts, $item, $args ) {
$atts['data-menuanchor'] = ( ! empty( $item->attr_title ) ) ? $item->attr_title : 'test';
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'menu_anchor_attributes', 10, 3 );
This way, if a title attribute hasn’t been filled into the back-end it will still display the attribute with a value of test
.