函数文档

get_language_attributes()

💡 云策文档标注

概述

get_language_attributes() 函数用于生成 HTML 标签的语言属性,包括文本方向和语言信息。它根据文档类型和站点设置返回一个空格分隔的属性字符串。

关键要点

  • 函数返回一个包含 dir 和 lang 或 xml:lang 属性的字符串,用于 'html' 标签。
  • 参数 $doctype 可选,接受 'xhtml' 或 'html',默认值为 'html',影响 lang 属性的输出格式。
  • 内部使用 is_rtl() 检测 RTL 方向,get_bloginfo('language') 获取语言代码,并通过 apply_filters('language_attributes') 提供过滤钩子。

代码示例

function get_language_attributes( $doctype = 'html' ) {
    $attributes = array();

    if ( function_exists( 'is_rtl' ) && is_rtl() ) {
        $attributes[] = 'dir="rtl"';
    }

    $lang = get_bloginfo( 'language' );
    if ( $lang ) {
        if ( 'text/html' === get_option( 'html_type' ) || 'html' === $doctype ) {
            $attributes[] = 'lang="' . esc_attr( $lang ) . '"';
        }

        if ( 'text/html' !== get_option( 'html_type' ) || 'xhtml' === $doctype ) {
            $attributes[] = 'xml:lang="' . esc_attr( $lang ) . '"';
        }
    }

    $output = implode( ' ', $attributes );

    /**
     * Filters the language attributes for display in the 'html' tag.
     *
     * @since 2.5.0
     * @since 4.3.0 Added the `$doctype` parameter.
     *
     * @param string $output A space-separated list of language attributes.
     * @param string $doctype The type of HTML document (xhtml|html).
     */
    return apply_filters( 'language_attributes', $output, $doctype );
}

注意事项

  • 函数自 WordPress 4.3.0 版本引入,并包含一个过滤钩子 language_attributes,允许开发者自定义输出。
  • 输出属性取决于站点语言设置和 HTML 文档类型,需确保正确配置 get_option('html_type') 和 $doctype 参数。

📄 原文内容

Gets the language attributes for the ‘html’ tag.

Description

Builds up a set of HTML attributes containing the text direction and language information for the page.

Parameters

$doctypestringoptional
The type of HTML document. Accepts 'xhtml' or 'html'. Default 'html'.

Return

string A space-separated list of language attributes.

Source

function get_language_attributes( $doctype = 'html' ) {
	$attributes = array();

	if ( function_exists( 'is_rtl' ) && is_rtl() ) {
		$attributes[] = 'dir="rtl"';
	}

	$lang = get_bloginfo( 'language' );
	if ( $lang ) {
		if ( 'text/html' === get_option( 'html_type' ) || 'html' === $doctype ) {
			$attributes[] = 'lang="' . esc_attr( $lang ) . '"';
		}

		if ( 'text/html' !== get_option( 'html_type' ) || 'xhtml' === $doctype ) {
			$attributes[] = 'xml:lang="' . esc_attr( $lang ) . '"';
		}
	}

	$output = implode( ' ', $attributes );

	/**
	 * Filters the language attributes for display in the 'html' tag.
	 *
	 * @since 2.5.0
	 * @since 4.3.0 Added the `$doctype` parameter.
	 *
	 * @param string $output A space-separated list of language attributes.
	 * @param string $doctype The type of HTML document (xhtml|html).
	 */
	return apply_filters( 'language_attributes', $output, $doctype );
}

Hooks

apply_filters( ‘language_attributes’, string $output, string $doctype )

Filters the language attributes for display in the ‘html’ tag.

Changelog

Version Description
4.3.0 Introduced.