Add custom attributes to menu items without plugin

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?

Related posts

2 comments

  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 );
    });
    
  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”

Comments are closed.