钩子文档

language_attributes

💡 云策文档标注

概述

language_attributes 是一个 WordPress 过滤器,用于修改 HTML 标签中的语言属性。它允许开发者自定义语言属性字符串,并支持指定文档类型参数。

关键要点

  • 过滤器名称:language_attributes
  • 参数:$output(语言属性字符串)和 $doctype(文档类型,如 xhtml 或 html)
  • 用途:在 get_language_attributes() 函数中应用,控制 HTML 标签的 lang 和 dir 等属性
  • 版本历史:从 2.5.0 引入,4.3.0 添加了 $doctype 参数

代码示例

function wpdocs_force_site_locale( $locale = 'en-US' ) {
    add_filter( 'language_attributes', function( $output ) use ( $locale ) {
        $lang_regex = '/lang="([a-zA-Z-_]+)"/';
        $output     = preg_replace( $lang_regex, 'lang="' . $locale . '"', $output );
        $xml_lang_regex = '/xml:lang="([a-zA-Z-_]+)"/';
        $output         = preg_replace( $xml_lang_regex, 'xml:lang="' . $locale . '"', $output );
        return $output;
    } );
}

注意事项

  • 用户贡献笔记指出,第二个 preg_replace 可能不必要,因为第一个已处理 xml:lang 属性
  • 使用此过滤器时,需确保不破坏其他属性如 dir

📄 原文内容

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

Parameters

$outputstring
A space-separated list of language attributes.
$doctypestring
The type of HTML document (xhtml|html).

Source

return apply_filters( 'language_attributes', $output, $doctype );

Changelog

Version Description
4.3.0 Added the $doctype parameter.
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Here is a function to force the locale of the HTML lang attribute without breaking the other attributes like dir

    /**
     * Forces the site locale for the HTML lang attribute.
     * 
     * @param string $locale the locale to set with the following format : "en-US"
     * @return void
     */
    function wpdocs_force_site_locale( $locale = 'en-US' ) {
    	add_filter( 'language_attributes', function( $output ) use ( $locale ) {
    		// match the lang attribute and replace it with the new locale
    		$lang_regex = '/lang="([a-zA-Z-_]+)"/';
    		$output     = preg_replace( $lang_regex, 'lang="' . $locale . '"', $output );
    
    		// update the xml:lang attribute as well
    		$xml_lang_regex = '/xml:lang="([a-zA-Z-_]+)"/';
    		$output         = preg_replace( $xml_lang_regex, 'xml:lang="' . $locale . '"', $output );
    		
    		return $output;
    	} );
    }