How to Add to Each Menu Link with link text to data-attr?

Solution 1: Using customize walker

I got some idea from add span class inside wp_nav_menu link anchor tag and made some changes for your requirements.

1. Add this code below to your functions.php first.

class Nav_Walker_Nav_Menu extends Walker_Nav_Menu{
  function start_el(&$output, $item, $depth, $args){
       global $wp_query;
       $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
       $class_names = $value="";
       $classes = empty( $item->classes ) ? array() : (array) $item->classes;
       $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
       $class_names=" class="". esc_attr( $class_names ) . '"';

       $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';

       $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
       $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
       $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
      $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';


       $description  = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';



        $item_output = $args->before;
        $item_output .= '<a'. $attributes .'><span data-hover="'. $item->title .'">';
        $item_output .=$args->link_before .apply_filters( 'the_title', $item->title, $item->ID );
        $item_output .= $description.$args->link_after;
        $item_output .= '</span></a>';
        $item_output .= $args->after;

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
}

2. Add code below to your header.php where your wp_nav_menu is installed.
Explained below is the code so it installs the new custom menu in this case would be Nav_Walker_Nav_Menu.

<?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary', 'walker' => new Nav_Walker_Nav_Menu() ) ); ?>

Hope this help you well!

Solution 2: Using wp_list_pages

Please check out this page . You can see their snippet. If you put the spans around the link tags you can use link_before and link_after

wp_list_pages("link_before=<span data-hover="link-text-here">&link_after=</span>");

Leave a Comment