Add custom attribute to menu item link using Filter

In order to increase my theme’s accessibility, I want to add the aria-current="page" attribute to the menu item that has the class .current_page_item.

As of right now, I am doing this via jQuery using the following:

var currentitem = $( '.current_page_item > a' );
currentitem.attr( 'aria-current', 'page' );

While this does what I want it to do, I would prefer that PHP handles this particular thing.

I know I can do this either with a custom Nav Walker class or with a filter to nav_menu_link_attributes. Unfortunately I have not seen any code even remotely near what I want to do.

function my_menu_filter( $atts, $item, $args, $depth ) {
   // Select the li.current_page_item element
   // Add `aria-current="page"` to child a element
}
add_filet( 'nav_menu_link_attributes', 'my_menu_filter', 10, 3 );

Any help in writing this filter would be appreciated.

2 Answers
2

You may target the current_page_item CSS class or you may target the current-menu-item CSS class instead. current_page_item class may not be present for all kinds of menu item. Read the answer here to know why.

Whichever CSS class you choose, you may use the CODE like the following to set the attribute:

add_filter( 'nav_menu_link_attributes', 'wpse260933_menu_atts_filter', 10, 3 );
function wpse260933_menu_atts_filter( $atts, $item, $args ) {
    if( in_array( 'current-menu-item', $item->classes ) ) {
        $atts['aria-current'] = 'page';
    }
    return $atts;
}

Leave a Comment