Add custom attribute to menu item link using Filter

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