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

Leave a Comment