I'm using fullpage.js on a wordpress site and would like to use one of it's function wicht is to add a class on a li. But to do this you need to add the data attribute data-menuanchor .
I have seen this:
add_filter( 'nav_menu_link_attributes', 'my_nav_menu_attribs', 10, 3 );
function my_nav_menu_attribs( $atts, $item, $args )
{
// The ID of the target menu item
$menu_target = 113;
// inspect $item
if ($item->ID == $menu_target) {
$atts['data-menuanchor'] = 's1';
}
return $atts;
}
It works excepts that it adds the attribute to the a tag and need it to be on the li tag.
Also, if I want to do it to all the items on the menu. Do I need to do this function for all the items? And I suppose I have to rename the function each time?
Thanks
I'm not sure WP has a specific filter/method for this. You're gonna have to do some manual DOM manipulation along with wp_nav_menu_items
.
https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/
function addDataAttr( $items, $args ) {
$dom = new DOMDocument();
$dom->loadHTML($items);
$find = $dom->getElementsByTagName('li');
foreach ($find as $item ) :
$item->setAttribute('data-menuanchor','s1');
endforeach;
return $dom->saveHTML();
}
add_filter('wp_nav_menu_items', 'addDataAttr', 10, 2);