admin管理员组

文章数量:1288005

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>
</ul>

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

Thanks,

Harvey

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>
</ul>

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

Thanks,

Harvey

Share Improve this question edited Feb 17, 2018 at 18:56 Den Isahac 9637 silver badges20 bronze badges asked Feb 17, 2018 at 17:20 HarveyHarvey 534 silver badges11 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

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 );

You can also try:

/*
 * Add filter attribute 
 */

add_filter( 'walker_nav_menu_start_el', 'modify_walker_data_attr', 10, 4);

function modify_walker_data_attr( $item_output, $item, $depth, $args )
{

    // I use ACF for adding field to a menu item
    // https://www.advancedcustomfields/resources/adding-fields-menu-items/
    $data_hover = get_field('data-hover', $item);

    $old = '<a';
    $new = '<a data-hover="'.$data_hover.'" ';

    $item_output = str_replace($old, $new, $item_output);

    return $item_output;
}

本文标签: phpMenu Custom Data Attributes