Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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 );
});
share|improve this answer
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. –  Magenta Cuda 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. –  toscho Jun 6 '13 at 22:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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