函数文档

_get_path_to_translation_from_lang_dir()

💡 云策文档标注

概述

_get_path_to_translation_from_lang_dir() 函数用于获取当前语言环境下翻译文件(.mo 文件)在语言目录中的路径。该函数已被弃用,建议使用 WP_Textdomain_Registry 替代。

关键要点

  • 函数已弃用:自 WordPress 6.1.0 起,使用 _deprecated_function() 标记,推荐迁移到 WP_Textdomain_Registry。
  • 参数:接受一个必需的字符串参数 $domain,表示文本域,用于唯一标识翻译字符串。
  • 返回值:返回翻译文件的路径字符串,如果未找到则返回 false。
  • 性能优化:通过静态变量 $cached_mofiles 缓存可用的 .mo 文件列表,提升查找效率。
  • 查找逻辑:在 WP_LANG_DIR 的 plugins 和 themes 子目录中搜索格式为 "{$domain}-{$locale}.mo" 的文件,其中 $locale 由 determine_locale() 确定。

代码示例

function _get_path_to_translation_from_lang_dir( $domain ) {
    _deprecated_function( __FUNCTION__, '6.1.0', 'WP_Textdomain_Registry' );

    static $cached_mofiles = null;

    if ( null === $cached_mofiles ) {
        $cached_mofiles = array();

        $locations = array(
            WP_LANG_DIR . '/plugins',
            WP_LANG_DIR . '/themes',
        );

        foreach ( $locations as $location ) {
            $mofiles = glob( $location . '/*.mo' );
            if ( $mofiles ) {
                $cached_mofiles = array_merge( $cached_mofiles, $mofiles );
            }
        }
    }

    $locale = determine_locale();
    $mofile = "{$domain}-{$locale}.mo";

    $path = WP_LANG_DIR . '/plugins/' . $mofile;
    if ( in_array( $path, $cached_mofiles, true ) ) {
        return $path;
    }

    $path = WP_LANG_DIR . '/themes/' . $mofile;
    if ( in_array( $path, $cached_mofiles, true ) ) {
        return $path;
    }

    return false;
}

注意事项

  • 该函数自 WordPress 6.1.0 起已弃用,新代码应避免使用,转而采用 WP_Textdomain_Registry 进行翻译文件管理。
  • 函数内部依赖 determine_locale() 获取当前语言环境,确保语言设置正确。
  • 缓存机制仅初始化一次,后续调用直接使用缓存列表,但需注意文件系统变化可能不会自动更新缓存。

📄 原文内容

Gets the path to a translation file in the languages directory for the current locale.

Description

Holds a cached list of available .mo files to improve performance.

See also

Parameters

$domainstringrequired
Text domain. Unique identifier for retrieving translated strings.

Return

string|false The path to the translation file or false if no translation file was found.

Source

function _get_path_to_translation_from_lang_dir( $domain ) {
	_deprecated_function( __FUNCTION__, '6.1.0', 'WP_Textdomain_Registry' );

	static $cached_mofiles = null;

	if ( null === $cached_mofiles ) {
		$cached_mofiles = array();

		$locations = array(
			WP_LANG_DIR . '/plugins',
			WP_LANG_DIR . '/themes',
		);

		foreach ( $locations as $location ) {
			$mofiles = glob( $location . '/*.mo' );
			if ( $mofiles ) {
				$cached_mofiles = array_merge( $cached_mofiles, $mofiles );
			}
		}
	}

	$locale = determine_locale();
	$mofile = "{$domain}-{$locale}.mo";

	$path = WP_LANG_DIR . '/plugins/' . $mofile;
	if ( in_array( $path, $cached_mofiles, true ) ) {
		return $path;
	}

	$path = WP_LANG_DIR . '/themes/' . $mofile;
	if ( in_array( $path, $cached_mofiles, true ) ) {
		return $path;
	}

	return false;
}

Changelog

Version Description
6.1.0 Deprecated.
4.7.0 Introduced.