这个问题很老了,但我自己在寻找答案时发现了它,我想我会回答,以防其他人来这里。
就我而言,我想将 aria-labels 添加到具有子项的菜单项中,因为在使用 VoiceOver 测试我的菜单时,我注意到需要更清楚地看到链接会打开下面的菜单。
Walker_Nav_Menu 类中有一个过滤器,用于处理菜单项的属性,nav_menu_link_attributes。 (在 wp-includes/class-walker-nav-menu.php 中)您可以使用它来编辑要添加到链接的属性数组。
如果链接 (a) 只是“#”并且 (b) 有子项,我的目标是在链接名称的末尾添加“菜单”一词。这对我有用,YMMV:
/* @see jcdesign_label_menu_items() */
add_filter( 'nav_menu_link_attributes', 'jcdesign_label_menu_items', 10, 4 );
/**
* Filter nav menu items
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* @type string $aria_current The aria-current attribute.
* }
* @param WP_Post $item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*
* @see Walker_Nav_Menu
*
* @return array
*/
function jcdesign_label_menu_items( $atts, $item, $args, $depth ) {
$empty_href = ( ! isset( $atts[ 'href' ] ) || $atts[ 'href' ] === '#' || $atts[ 'href' ] === '' );
$has_children = ( is_array( $item->classes ) && in_array( 'menu-item-has-children', $item->classes ) );
// If href is essentially empty, and the item has children,
// add an aria label noting that this is a menu
if ( $empty_href && $has_children ) {
$atts[ 'aria-label' ] = strip_tags( $item->title ) . ' Menu';
}
return $atts;
}
我没有使用 $args 或 $depth 参数,所以我可以不使用它们,但是将它们放置在适当的位置意味着我知道如果我下次要获取此代码,我可以使用它们。