2

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?

6

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 );
});
  • 1
    I was surprised to see this filter as I had just been reading the nav menu source code and did not notice it. It is in the beta version 3.6.0 but not in the production version 3.5.1. The old filter 'walker_nav_menu_start_el' might also work. – user27457 May 26 '13 at 13:55
  • I've tried adding this function into my code, but for some reason it's not doing anything. Is there additional code I need to write for it? – Jake Lisby May 30 '13 at 14:10
  • @JakeLisby Sorry, the first code I posted works in 3.6 only. I made an update with an alternative. – fuxia Jun 6 '13 at 22:07
0

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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