I’m trying to figure out the best way to add custom menu attributes without using a plugin. I have a site using a custom theme and need to make sure this is setup at theme activation vs needing to setup a plugin as well.
Is there a function I can plug into for this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Filter nav_menu_link_attributes:
add_filter( 'nav_menu_link_attributes', 'wpse_100726_extra_atts', 10, 3 );
function wpse_100726_extra_atts( $atts, $item, $args )
{
// inspect $item, then …
$atts['custom'] = 'some value';
return $atts;
}
This works with WordPress < 3.6:
add_filter( 'walker_nav_menu_start_el', function( $item ) {
$parts = explode( '>', $item );
$out = array ();
foreach ( $parts as $i => $part )
{
if ( 0 === strpos( $part, '<a ' ) ) // a start
$out[ $i ] = $part . ' data-foo="bar"';
else
$out[ $i ] = $part;
}
return join( '>', $out );
});
Method 2
it is nice work. but i want to little bit extra more, trying but can not figure out yet how.
add_filter( 'nav_menu_link_attributes', 'wpse_100726_extra_atts', 10, 3 );
function wpse_100726_extra_atts( $atts, $item, $args )
{
// inspect $item, then …
$atts['data-hover'] = 'some value';
return $atts;
}
i want some value change to menu items name. ex data-hover=”contact us”
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0