How to Add Custom Attribute to WordPress menu item

Here’s an issue that I recently solved on my client website. The WordPress navigation menu has a dropdown that works perfectly fine in desktop browsers, while on mobile – if I click on the drop-down arrow, the menu expands and does nothing when the menu text is clicked. The solution is to add a custom attribute to the WordPress menu item. Before we talk about the solution, have a look at the below screenshot that explains the issue.

wordpress nav dropdown menu issue

I used Chrome Inspect  to understand the difference between the anchor tag that encapsulates the menu text and the drop-down arrow. Here’s the snapshot of the same.

Add Custom Attribute to WordPress menu item

The difference I noticed was the attribute data-toggle="dropdown" , which is missing in the anchor tag of the menu text, and it was the issue. Adding the attribute data-toggle="dropdown" to the anchor tag of the menu text will solve the issue. So how did I add this custom attribute to the menu item? Here’s how it’s done.

How to Add custom attribute to WordPress menu item

We need to hook our code of adding a custom attribute using the nav_menu_link_attributes filter of WordPress. Add the below code in your WordPress theme’s functions.php.

add_filter( 'nav_menu_link_attributes', 'tg_atts', 10, 3 );

function tg_atts( $atts, $item, $args )
{
// inspect $item, then …
$atts['data-toggle'] = 'dropdown';
return $atts;
}

The above code will add the custom attribute to all the menu items. But I really do not want to that, as I need the custom attribute added only to the drop-down menu items and not for all. So all I need to do is, add a condition to check the menu item ID and add the custom attribute only to that. Below is the modified code.

add_filter( 'nav_menu_link_attributes', 'wpse_100726_extra_atts', 10, 3 );

function wpse_100726_extra_atts( $atts, $item, $args )
{
if( $item->ID == "776" || $item->ID == "777" ) {
$atts['data-toggle'] = 'dropdown';
return $atts;
}
}

That’s it! Now it works perfectly fine.

Updated on May 19, 2020

Was this article helpful?

Related Articles

Comments

  1. I read this post because I have a food delivery website and have an issue i am facing with WPbakery Page builder. I read online that i can add Anchor Links to a wordpress website where a user can click on a link on a menu and it will redirect the user to the section where it is on the website/webpage.

    I have been searching online without success on how to do the reverse where if a user clicks on a link on the website or webpage it takes the user to the select menu where i want the user to click on.

    I want to know if this can be done, and if so, is there a tutorial where i can get to know how to do this with WPBakery Page builder.

Leave a Comment