• Hello all!

    Is it possible to add in specific attributes (such as role) to the menus on the navigation bar? If so, how would I be able to do so?

    Thanks!

Viewing 1 replies (of 1 total)
  • We need to look at this Huge Monster – WP_Nav Walker. It looks massive but one you get the hang of it, it’s not too bad:

    /** The Walker **/
    class Texas_Ranger extends Walker_Nav_Menu {
    
        // add main/sub classes to li's and links
         function start_el( &$output, $item, $depth, $args ) {
            global $wp_query;
            $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
    
            // passed classes
            $classes = empty( $item->classes ) ? array() : (array) $item->classes;
    
            $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
    
            // build html
            $output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="' . $class_names . '">';
    
            // link attributes
            $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
            $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
            $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
            $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
            $attributes .= ' class="menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"';
    
            $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
                $args->before,
                $attributes,
                $args->link_before,
                apply_filters( 'the_title', $item->title, $item->ID ),
                $args->link_after,
                $args->after
            );
    
            // build html
            $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
        }
    }

    So you can append onto the attributes section like so:

    $attributes .= ' target="_blank"';

    Then you can add that to you custom nav menu via:

    wp_nav_menu( array(
    	'walker'	=> new Texas_Ranger()
    ) );
Viewing 1 replies (of 1 total)

The topic ‘Adding attributes to menus on navigation bar’ is closed to new replies.