I'm trying to add a custom data attribute to the <a> element. What I'm trying to do is integrate the navigation effect in this CodePen

I can do all the CSS but I need to add the HTML part such as below:

   <ul class="snip1226">
  <li class="current"><a href="#" data-hover="Home">Home</a></li>
  <li><a href="#" data-hover="About Us">About Us</a></li>
  <li><a href="#" data-hover="Blog">Blog</a></li>
  <li><a href="#" data-hover="Services">Services</a></li>
  <li><a href="#" data-hover="Products">Products</a></li>
  <li><a href="#" data-hover="Contact">Contact</a></li>

How and where would I add this into WordPress? What would I need to edit to add this HTML functionally?




If you want to add a custom data attributes to the menu that's generated by wp_nav_menu function. You can use the nav_menu_link_attributes filter to add the desired attributes to the <a> elements.

function add_menu_atts( $atts, $item, $args ) {
    $atts['data-hover'] = $atts['title']; // add data-hover attribute

    return $atts;
add_filter( 'nav_menu_link_attributes', 'add_menu_atts', 10, 3 );
  • Okay thank you, I will give that a go. Should adding this work just like how the HTML would work? – Harvey Feb 17 '18 at 21:07
  • @Harvey that would work as the CodePen example, however please update the CSS to match the selectors generated by wp_nav_menu. For example: the current class to mark the active <li> element, in WordPress that would be current-menu-item – Den Isahac Feb 17 '18 at 22:23
  • Okay that’s what I’ve been doing so will give it a try this morning :) – Harvey Feb 18 '18 at 8:28
  • Hi, I have added the above code into the functions.php of the child theme which I think is correct? Then I have edited the CSS selector to be '.main-navigation ul.menu' I tired replacing the sector with the current-menu-item but didnt get any of it working – Harvey Feb 18 '18 at 9:05
  • I have just uploaded the site, sorry if it is slow as its in early development derbyshiregas.co.uk – Harvey Feb 18 '18 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.