【问题标题】:Adding 'aria-labels' to anchor links in WordPress navigation menu将“aria-labels”添加到 WordPress 导航菜单中的锚链接
【发布时间】:2017-07-26 18:37:24
【问题描述】:

我需要为我的 WordPress 网站中的每个菜单(和子菜单)项添加自定义 aria-labels。它正在运行一个自定义主题。

我希望 aria-labels 包含这样的页面标题:

aria-label="页面标题"

因此,导航菜单结构中的每个 LI 最终都会如下所示:

<li id="id_name" class="class_names"><a href="http://linktothepage.com/page" aria-label="TITLE OF MY PAGE">TITLE OF MY PAGE</a></li>

最有效的方法是什么? 过滤器? 还有什么?

【问题讨论】:

  • 为什么要加aria-labels?在您提供的示例中,它只是重复了屏幕阅读器在没有它们的情况下会宣布的内容(链接文本)。

标签: wordpress accessibility wai-aria


【解决方案1】:

你必须在&lt;a&gt; 标签中有一个title 属性,那么你真的不需要aria-label 属性。所有屏幕阅读器都会自动读取标签的标题。

aria-label 可能是必需的,以防您的内容不是纯文本而是更多的 HTML 代码。

当你点击任何链接时,必须添加 attr aria-selected="true"

所以最终结果是:

<li id="id_name" class="class_names">
    <a href="http://linktothepage.com/page" title="TITLE OF MY PAGE">TITLE OF MY PAGE</a>
</li>

如果页面加载时的导航菜单项是选中项,则:

<li id="id_name" class="class_names">
    <a href="http://linktothepage.com/page" title="TITLE OF MY PAGE" aria-selected="true">TITLE OF MY PAGE</a>
</li>

【讨论】:

【解决方案2】:

这个问题很老了,但我自己在寻找答案时发现了它,我想我会回答,以防其他人来这里。

就我而言,我想将 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 参数,所以我可以不使用它们,但是将它们放置在适当的位置意味着我知道如果我下次要获取此代码,我可以使用它们。

【讨论】:

  • 工作就像一个魅力
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 2014-01-12
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
相关资源
最近更新 更多