钩子文档

locale

💡 云策文档标注

概述

locale 过滤器用于修改 WordPress 安装的区域设置 ID,允许开发者动态调整语言环境。此 Hook 在 get_locale() 函数中被调用,可用于强制指定语言,例如在管理后台使用特定语言。

关键要点

  • locale 过滤器接受一个字符串参数 $locale,表示当前区域设置 ID,返回修改后的区域设置 ID。
  • 此 Hook 从 WordPress 1.5.0 版本引入,常用于自定义语言逻辑,如基于用户角色或页面类型切换语言。
  • 使用此 Hook 时,建议在插件中调用而非主题中,以确保在 WordPress 加载主题前生效。

代码示例

// 强制在 WordPress 管理后台使用英语(en_US)
if ( ! function_exists( 'uniquePrefix_force_english_only_admin' ) ) {
    function uniquePrefix_force_english_only_admin( $locale ) {
        if ( is_admin() ) {
            $locale = 'en_US';
        }
        return $locale;
    }
    add_filter( 'locale', 'uniquePrefix_force_english_only_admin', 1, 1 );
}

注意事项

  • locale 过滤器在 get_locale() 函数中应用,影响整个 WordPress 的区域设置,需谨慎使用以避免冲突。
  • 用户贡献笔记提供了实际应用示例,如基于 URL 参数或管理后台条件修改语言,但需注意代码兼容性和安全性。

📄 原文内容

Filters the locale ID of the WordPress installation.

Parameters

$localestring
The locale ID.

Source

return apply_filters( 'locale', $locale );

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    You can leverage this hook to force the language of your admin dashboard, however, you need to call it from a plugin and not from your theme, by the time WordPress gets to loading your theme it’s too late.

    http://your-domain.com</a>
    Description: Force English (en_US) in the WordPress Admin
    Version: 1.0
    Author: You
    Author URI: <a href="http://your-domain.com" rel="nofollow ugc">http://your-domain.com</a>
    Text Domain: englishonlyadmin
    */
    
    // prevent direct access
    if ( ! defined( 'WPINC' ) ) {
        die;
    }
    
    if ( ! function_exists( 'uniquePrefix_force_english_only_admin' ) ) {
        /**
         * Override locale for admin to force English (en_US).
         *
         * @param string $locale Current locale.
         *
         * @return string English (en_US) locale if in Admin, configured locale otherwise.
         */
        function uniquePrefix_force_english_only_admin( $locale ) {
            // detect when we are in the admin dashboard and force english
            if ( is_admin() ) {
                $locale = 'en_US';
            }
    
            return $locale;
        }
    
        add_filter( 'locale', 'uniquePrefix_force_english_only_admin', 1, 1 );
    }