Want to add a custom attribute like target="foobox"
or data-featherlight="#enews-popup"
to a specific nav menu item’s anchor?
nav_menu_link_attributes filter hook in WordPress is your friend.
For example, adding
/**
* Add custom attribute and value to a nav menu item's anchor.
*
* @author Sridhar Katakam
* @link https://sridharkatakam.com/
*/
add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args ) {
if ( 1161 === $item->ID ) { // change 1161 to the ID of your menu item.
$atts['target'] = 'foobox';
}
return $atts;
}, 10, 3 );
in child theme’s functions.php will add target="foobox"
to the menu item 1161’s a element.
Replace 1161
with the ID of your menu item. This can be obtained by inspecting it using Chrome’s Developer Tools.
Here’s a better version which does not rely on entering the menu item ID:
Simply assign a class to the menu item, say target-foobox
and use this code:
/**
* Add custom attribute and value to a nav menu item's anchor based on CSS class.
*
* @author Sridhar Katakam
* @link https://sridharkatakam.com/
*/
add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args ) {
if ( 'target-foobox' === $item->classes[0] ) {
$atts['target'] = 'foobox';
}
return $atts;
}, 10, 3 );