how to add data attribute to a <li> element in wordpress nav menu

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:

Read More
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

Related posts

3 comments

  1. 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);
    
  2. I solved this, using the custom links and getting the url entered in the link as an attribute and replacing the # character with empty. The following code must be entered in the file functions.php:

    add_filter( 'nav_menu_link_attributes', 'add_data_atts_to_nav', 10, 4 );
        function add_data_atts_to_nav( $atts, $item, $args ) {
        $atts['data-menuanchor'] = strtolower(str_replace("#","",$item->url));
        return $atts;
    }
    

    Attached screenshot of my menu.

    Any questions tell me and I gladly help them.

    Luck.

    enter image description here

  3. Actually i was searching for a similar thing for fullpage.js navigation,i managed it setting up a filter that get the pre-existing title-attr customizable from backend and assign it to ‘data-menuanchor’ just to keep it at least a minimum scalable and mantainable even if i have to add something new.

    Here’s what i’ve used.

    function add_specific_menu_atts( $atts, $item, $args ) {
    
      $atts['data-menuanchor'] = $item->attr_title;
    
    
    return $atts;
    
    }
    
    add_filter( 'nav_menu_link_attributes', 'add_specific_menu_atts', 10, 3 );
    

Comments are closed.