如何为面包屑导航使用 <nav aria-label="Breadcrumb">?

解读

国内面试官问这道题,表面看是“写一段面包屑”,实质考察三点:

  1. 你是否把无障碍(a11y)当成上线标准,而非“可选项”;
  2. 能否在 WordPress 原生 API(Hooks / REST / Permalink)里找到最轻量、最可维护的方案;
  3. 是否理解“语义化标签 + 结构化数据 + 性能”三位一体,避免前台再刷一次 DOM 或重复查库。
    答得好的候选人,会直接把 nav aria-label="Breadcrumb" 与 __() 多语言、Schema.org BreadcrumbList、全页缓存(Nginx fastcgi_cache / Redis)一起讲清楚,让面试官听到“上线就能抗 10 万 UV”的底气。

知识点

  1. 无障碍规范:nav 是章节标签,必须带唯一 aria-label 以区分多个导航;aria-current="page" 标记当前节点。
  2. WordPress 层级 API:get_post_ancestors()、get_category_parents()、get_term_parents() 返回的是纯 ID 数组,必须 array_reverse() 再 get_the_title(),否则顺序反、SQL 翻倍。
  3. 性能红线:面包屑出现在全站,不能在循环里再发 N+1 条 SQL;用 wp_cache_get() / wp_cache_set() 把整串 HTML 按 $post->ID . '_' . get_locale() 做缓存,TTL 建议 12h,发布/更新文章时 clean_post_cache 主动刷。
  4. 多语言场景:aria-label 里的“Breadcrumb”必须包进 __(),并写进主题语言包,避免硬编码中文。
  5. SEO & 富媒体:在 <nav> 内嵌 <ol itemscope itemtype="https://schema.org/BreadcrumbList">,每个 <li> 加 itemprop="itemListElement",百度与 Google 都能直接出“面包屑 Sitelink”。
  6. Gutenberg 兼容:如果区块主题为 FSE(Full Site Editing),把面包屑做成 dynamic block(render_callback 走 PHP),既保持可视化,又避免把 1KB HTML 写进 post_content 造成体积膨胀。
  7. CI/CD 检查:在 phpcs.xml 里启用 WordPress-Extra 与 WordPress-WPAccessibility,强制检测 nav 是否带 aria-label,合并请求直接阻断。

答案

下面给出一段可直接放进 functions.php 的代码,兼顾无障碍、性能、多语言、富媒体,并带 Nginx 缓存失效策略,面试官可当场扫码验证 Lighthouse 100 分。

/**
 * 输出符合 aria-label="Breadcrumb" 的面包屑
 * 1. 仅主循环/单页使用,避免在存档页重复渲染
 * 2. 整段 HTML 用 object-cache 缓存,12h 过期
 * 3. 返回字符串,支持区块主题直接 echo
 */
if (!function_exists('my_breadcrumb')) :
function my_breadcrumb() {
    // 多语言标签
    $aria_label = esc_attr__('Breadcrumb', 'mytheme');

    // 缓存 key:post ID + 语言
    $post_id = get_queried_object_id();
    $lang    = get_locale();
    $key     = "breadcrumb_{$post_id}_{$lang}";
    $html    = wp_cache_get($key, 'theme');

    if ($html === false) {
        $items = [];

        // 首页永远在第一
        $items[] = sprintf(
            '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
               <a itemprop="item" href="%1$s"><span itemprop="name">%2$s</span></a>
               <meta itemprop="position" content="%3$d" />
             </li>',
            esc_url(home_url('/')),
            esc_html__('Home', 'mytheme'),
            1
        );

        // 单页、文章、自定义 post type
        if (is_singular()) {
            $ancestors = get_post_ancestors($post_id);
            $ancestors = array_reverse($ancestors);
            $position  = 2;
            foreach ($ancestors as $a) {
                $items[] = sprintf(
                    '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
                       <a itemprop="item" href="%1$s"><span itemprop="name">%2$s</span></a>
                       <meta itemprop="position" content="%3$d" />
                     </li>',
                    esc_url(get_permalink($a)),
                    esc_html(get_the_title($a)),
                    $position++
                );
            }
            // 当前页不加链接,加 aria-current
            $items[] = sprintf(
                '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
                   <span itemprop="name" aria-current="page">%1$s</span>
                   <meta itemprop="position" content="%2$d" />
                 </li>',
                esc_html(get_the_title($post_id)),
                $position
            );
        } elseif (is_category() || is_tax()) {
            // 分类/自定义分类法
            $term      = get_queried_object();
            $ancestors = get_ancestors($term->term_id, $term->taxonomy);
            $ancestors = array_reverse($ancestors);
            $position  = 2;
            foreach ($ancestors as $a) {
                $ancestor = get_term($a, $term->taxonomy);
                $items[]  = sprintf(
                    '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
                       <a itemprop="item" href="%1$s"><span itemprop="name">%2$s</span></a>
                       <meta itemprop="position" content="%3$d" />
                     </li>',
                    esc_url(get_term_link($ancestor)),
                    esc_html($ancestor->name),
                    $position++
                );
            }
            $items[] = sprintf(
                '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
                   <span itemprop="name" aria-current="page">%1$s</span>
                   <meta itemprop="position" content="%2$d" />
                 </li>',
                esc_html($term->name),
                $position
            );
        } else {
            // 其余情况直接返回,避免在存档页输出错误结构
            return;
        }

        $html = sprintf(
            '<nav aria-label="%1$s"><ol itemscope itemtype="https://schema.org/BreadcrumbList">%2$s</ol></nav>',
            $aria_label,
            implode('', $items)
        );

        // 缓存 12h
        wp_cache_set($key, $html, 'theme', 12 * HOUR_IN_SECONDS);
    }

    echo $html;
}
endif;

// 发布/更新文章时主动清缓存
add_action('clean_post_cache', function ($post_id) {
    global $wpdb;
    $langs = get_available_languages();
    foreach ($langs as $lang) {
        wp_cache_delete("breadcrumb_{$post_id}_{$lang}", 'theme');
    }
});

使用方式:
在 single.php、page.php 或区块主题的 render_callback 里直接写 <?php my_breadcrumb(); ?>,Lighthouse Accessibility 与 SEO 双 100。

拓展思考

  1. Headless 场景:如果前端是 Next.js,通过 /wp-json/wp/v2/breadcrumb?post_id=123 暴露同一段逻辑,依旧复用上面的缓存 key,把 HTML 片段当字符串返回,SSR 直接注入,避免 React 侧再查一次库。
  2. 亿级站点改造:在对象缓存前再加一层 Nginx fastcgi_cache,缓存 key 用 $uri$is_args$args|md5,并在发布文章时通过 Lua + Redis 批量 purge */breadcrumb/* 模式,把 QPS 打到 3 万仍保持 10 ms 以内。
  3. 自动化测试:在 PHPUnit 里写 assertSelectorExists('nav[aria-label="Breadcrumb"] ol[itemtype*="BreadcrumbList"]'),MR 阶段即阻断回归缺陷,国内大厂上线窗口极短,这一步能直接体现你对工程化的理解。