0

Looking to add a data attribute to a list item in a menu, I can see that some threads on here can add it to the actual <a> link tag, I am looking to add it to the list item itself <li>

So this code adds the attribute to the <a>tag

add_filter( 'nav_menu_link_attributes', 'themeprefix_menu_attribute_add', 10, 3 );
function themeprefix_menu_attribute_add( $atts, $item, $args ) {
  // Set the menu ID
  $menu_link1 = 20;

// Conditionally match the ID and add the attribute and value
if ($item->ID == $menu_link1) {
$atts['data-content'] = 'about';

//Return the new attribute
return $atts;

Any ideas how to add the attribute to the <li> without using jQuery.

1
  • You can follow this link. hope it will helped.
    – Arman H
    Oct 14, 2021 at 5:28

2 Answers 2

0

try this code in your functions file.

function add_class_to_nav_items($nav_items, $args) {
  if ( $args['theme_location'] == 'MY_NAV_THEME_LOCATION' ) { // IMPORTANT: replace MY_NAV_THEME_LOCATION with the location of your menu
    foreach ($nav_items as &$nav_item) {
      $nav_item->classes[] = 'custon-class-name';
    }
  }

  return $nav_items;

}

add_filter( 'wp_nav_menu_objects', 'add_class_to_nav_items', 11 );
1
  • Original question asks for adding attributes to li tag
    – neilgee
    Feb 14, 2017 at 23:16
0

there is no filter available to add a custom attribute to the li element. only way possible is to use a custom walker.

here is how: (functions.php or custom plugin)

class so244415_custom_walker extends Walker_Nav_Menu {
    public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        //your code here. the line you want to edit is:
        //$output .= $indent . '<li' . $id . $class_names .'>';
    }
}

look for the file class-walker-nav-menu.php inside wp-includes and copy everything from the certain function start_el in there and edit it to your needs.

you would call your menu like so: (in the theme file, where you call your menu)

wp_nav_menu( array(
    'walker' => new so244415_custom_walker( $args ), /*( $args ) is optional...*/ 
));

another option would be, to use

function so244415_walker_nav_menu_start_el($item_output, $item, $depth, $args) {
    //some regex/str_replace here
    return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'so244415_walker_nav_menu_start_el', 10, 4);    

but i am not the biggest fan of this solution, since regex and suchlike is not the best way to edit html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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