函数文档

_navigation_markup()

💡 云策文档标注

概述

_navigation_markup() 是一个 WordPress 函数,用于将传入的链接包裹在导航标记中,生成符合可访问性标准的 HTML 结构。它支持自定义 CSS 类、屏幕阅读器文本和 ARIA 标签,并可通过过滤器钩子修改模板。

关键要点

  • 函数接受四个参数:$links(必需,导航链接字符串)、$css_class(可选,导航元素的 CSS 类,默认 'posts-navigation')、$screen_reader_text(可选,屏幕阅读器文本,默认 'Posts navigation')、$aria_label(可选,ARIA 标签,默认与 $screen_reader_text 相同)。
  • 返回一个字符串,即导航模板标签,使用 sprintf() 格式化输出,包含 sanitize_html_class()、esc_html() 和 esc_attr() 进行安全转义。
  • 提供过滤器钩子 'navigation_markup_template',允许开发者自定义导航标记的 HTML 模板,模板必须包含占位符 %1$s(CSS 类)、%2$s(屏幕阅读器文本)、%3$s(链接)、%4$s(ARIA 标签)。
  • 函数在 WordPress 4.1.0 引入,5.3.0 版本添加了 $aria_label 参数,常用于 get_the_posts_navigation() 等相关函数中。

代码示例

注意事项

  • 确保传入的 $links 参数是有效的 HTML 链接字符串,函数不会自动生成链接内容。
  • 使用过滤器时,自定义模板必须严格遵循占位符顺序,以保持可访问性和功能完整性。
  • 函数内部使用翻译函数 __() 处理默认文本,支持国际化,开发者可覆盖默认值提供本地化字符串。

📄 原文内容

Wraps passed links in navigational markup.

Parameters

$linksstringrequired
Navigational links.
$css_classstringoptional
Custom class for the nav element.
Default 'posts-navigation'.
$screen_reader_textstringoptional
Screen reader text for the nav element.
Default ‘Posts navigation’.
$aria_labelstringoptional
ARIA label for the nav element.
Defaults to the value of $screen_reader_text.

Return

string Navigation template tag.

Source

function _navigation_markup( $links, $css_class = 'posts-navigation', $screen_reader_text = '', $aria_label = '' ) {
	if ( empty( $screen_reader_text ) ) {
		$screen_reader_text = /* translators: Hidden accessibility text. */ __( 'Posts navigation' );
	}
	if ( empty( $aria_label ) ) {
		$aria_label = $screen_reader_text;
	}

	$template = '
	<nav class="navigation %1$s" aria-label="%4$s">
		<h2 class="screen-reader-text">%2$s</h2>
		<div class="nav-links">%3$s</div>
	</nav>';

	/**
	 * Filters the navigation markup template.
	 *
	 * Note: The filtered template HTML must contain specifiers for the navigation
	 * class (%1$s), the screen-reader-text value (%2$s), placement of the navigation
	 * links (%3$s), and ARIA label text if screen-reader-text does not fit that (%4$s):
	 *
	 *     <nav class="navigation %1$s" aria-label="%4$s">
	 *         <h2 class="screen-reader-text">%2$s</h2>
	 *         <div class="nav-links">%3$s</div>
	 *     </nav>
	 *
	 * @since 4.4.0
	 *
	 * @param string $template  The default template.
	 * @param string $css_class The class passed by the calling function.
	 */
	$template = apply_filters( 'navigation_markup_template', $template, $css_class );

	return sprintf( $template, sanitize_html_class( $css_class ), esc_html( $screen_reader_text ), $links, esc_attr( $aria_label ) );
}

Hooks

apply_filters( ‘navigation_markup_template’, string $template, string $css_class )

Filters the navigation markup template.

Changelog

Version Description
5.3.0 Added the aria_label parameter.
4.1.0 Introduced.