钩子文档

load_textdomain_mofile

💡 云策文档标注

概述

load_textdomain_mofile 是一个 WordPress 过滤器,用于在加载特定文本域的翻译时修改 MO 文件路径。它允许开发者自定义或覆盖默认的翻译文件位置。

关键要点

  • 过滤器名称:load_textdomain_mofile
  • 参数:$mofile(MO 文件路径字符串)和 $domain(文本域字符串)
  • 用途:通过 apply_filters 调用,可动态调整翻译文件的加载路径
  • 相关函数:与 load_textdomain() 配合使用,用于加载 .mo 文件到指定文本域
  • 引入版本:WordPress 2.9.0

代码示例

add_filter( 'load_textdomain_mofile', 'my_custom_translation_file', 10, 2 );

function my_custom_translation_file( $mofile, $domain ) {
  if ( 'textdomain' === $domain ) {
    $mofile = WP_LANG_DIR . '/textdomain/yourtranslationfile-' . get_locale() . '.mo';
  }
  return $mofile;
}

注意事项

  • 示例中需将 'textdomain' 替换为实际插件文本域,如 'hello-dolly'
  • 自定义文件路径应基于 WP_LANG_DIR 和 get_locale() 构建,确保与语言环境匹配
  • 此过滤器可用于覆盖插件默认翻译,实现多语言定制

📄 原文内容

Filters MO file path for loading translations for a specific text domain.

Parameters

$mofilestring
Path to the MO file.
$domainstring
Text domain. Unique identifier for retrieving translated strings.

Source

$mofile = apply_filters( 'load_textdomain_mofile', $mofile, $domain );

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    An example that allows to override the default translations of a plugin:

    add_filter( 'load_textdomain_mofile', 'my_custom_translation_file', 10, 2 );
    
    /*
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'hello-dolly'. 
     * Define your filename, such as: yourtranslationfile-en_GB.mo
     * Define the location, for example: wp-content/languages/textdomain/yourtranslationfile-en_GB.mo
     */
    function my_custom_translation_file( $mofile, $domain ) {
      if ( 'textdomain' === $domain ) {
        $mofile = WP_LANG_DIR . '/textdomain/yourtranslationfile-' . get_locale() . '.mo';
      }
      return $mofile;
    }