函数文档

load_script_textdomain()

💡 云策文档标注

概述

load_script_textdomain() 函数用于加载脚本的翻译字符串,返回 JSON 编码的翻译数据或失败时返回 false。它通过处理脚本句柄、文本域和路径参数,结合 WordPress 的翻译文件系统来定位和加载翻译文件。

关键要点

  • 函数参数:$handle(必需,脚本句柄)、$domain(可选,文本域,默认 'default')、$path(可选,翻译文件目录路径)。
  • 返回值:成功时返回 JSON 编码的翻译字符串,失败时返回 false。
  • 依赖关系:使用 WP_Scripts、WP_Textdomain_Registry、determine_locale() 等核心组件和函数。
  • 文件定位:基于脚本源 URL 和路径逻辑,自动确定翻译文件的相对路径和语言目录。
  • Hook:提供 load_script_textdomain_relative_path 过滤器,允许自定义脚本相对路径。
  • 相关函数:包括 load_script_translations()、wp_scripts() 等,用于辅助翻译加载过程。

代码示例

function load_script_textdomain( $handle, $domain = 'default', $path = '' ) {
    /** @var WP_Textdomain_Registry $wp_textdomain_registry */
    global $wp_textdomain_registry;

    $wp_scripts = wp_scripts();

    if ( ! isset( $wp_scripts->registered[ $handle ] ) ) {
        return false;
    }

    $locale = determine_locale();

    if ( ! $path ) {
        $path = $wp_textdomain_registry->get( $domain, $locale );
    }

    $path = untrailingslashit( $path );

    // If a path was given and the handle file exists simply return it.
    $file_base       = 'default' === $domain ? $locale : $domain . '-' . $locale;
    $handle_filename = $file_base . '-' . $handle . '.json';

    if ( $path ) {
        $translations = load_script_translations( $path . '/' . $handle_filename, $handle, $domain );

        if ( $translations ) {
            return $translations;
        }
    }

    // 后续代码处理脚本源 URL 和路径逻辑...
}

注意事项

  • 确保脚本已通过 wp_register_script() 或 wp_enqueue_script() 注册,否则函数可能返回 false。
  • 翻译文件命名遵循特定模式,如 {domain}-{locale}-{handle}.json 或基于 MD5 哈希的文件名。
  • 函数内部处理了自定义插件/主题路径和多站点配置,确保翻译文件正确加载。
  • 使用 load_script_textdomain_relative_path 过滤器可以调整脚本相对路径的计算方式。

📄 原文内容

Loads the script translated strings.

Description

See also

Parameters

$handlestringrequired
Name of the script to register a translation domain to.
$domainstringoptional
Text domain. Default 'default'.
$pathstringoptional
The full file path to the directory containing translation files.

Return

string|false The translated strings in JSON encoding on success, false if the script textdomain could not be loaded.

Source

function load_script_textdomain( $handle, $domain = 'default', $path = '' ) {
	/** @var WP_Textdomain_Registry $wp_textdomain_registry */
	global $wp_textdomain_registry;

	$wp_scripts = wp_scripts();

	if ( ! isset( $wp_scripts->registered[ $handle ] ) ) {
		return false;
	}

	$locale = determine_locale();

	if ( ! $path ) {
		$path = $wp_textdomain_registry->get( $domain, $locale );
	}

	$path = untrailingslashit( $path );

	// If a path was given and the handle file exists simply return it.
	$file_base       = 'default' === $domain ? $locale : $domain . '-' . $locale;
	$handle_filename = $file_base . '-' . $handle . '.json';

	if ( $path ) {
		$translations = load_script_translations( $path . '/' . $handle_filename, $handle, $domain );

		if ( $translations ) {
			return $translations;
		}
	}

	$src = $wp_scripts->registered[ $handle ]->src;

	if ( ! preg_match( '|^(https?:)?//|', $src ) && ! ( $wp_scripts->content_url && str_starts_with( $src, $wp_scripts->content_url ) ) ) {
		$src = $wp_scripts->base_url . $src;
	}

	$relative       = false;
	$languages_path = WP_LANG_DIR;

	$src_url     = wp_parse_url( $src );
	$content_url = wp_parse_url( content_url() );
	$plugins_url = wp_parse_url( plugins_url() );
	$site_url    = wp_parse_url( site_url() );
	$theme_root  = get_theme_root();

	// If the host is the same or it's a relative URL.
	if (
		( ! isset( $content_url['path'] ) || str_starts_with( $src_url['path'], $content_url['path'] ) ) &&
		( ! isset( $src_url['host'] ) || ! isset( $content_url['host'] ) || $src_url['host'] === $content_url['host'] )
	) {
		// Make the src relative the specific plugin or theme.
		if ( isset( $content_url['path'] ) ) {
			$relative = substr( $src_url['path'], strlen( $content_url['path'] ) );
		} else {
			$relative = $src_url['path'];
		}
		$relative = trim( $relative, '/' );
		$relative = explode( '/', $relative );

		/*
		 * Ensure correct languages path when using a custom `WP_PLUGIN_DIR` / `WP_PLUGIN_URL` configuration,
		 * a custom theme root, and/or using Multisite with subdirectories.
		 * See https://core.trac.wordpress.org/ticket/60891 and https://core.trac.wordpress.org/ticket/62016.
		 */

		$theme_dir = array_slice( explode( '/', $theme_root ), -1 );
		$dirname   = $theme_dir[0] === $relative[0] ? 'themes' : 'plugins';

		$languages_path = WP_LANG_DIR . '/' . $dirname;

		$relative = array_slice( $relative, 2 ); // Remove plugins/<plugin name> or themes/<theme name>.
		$relative = implode( '/', $relative );
	} elseif (
		( ! isset( $plugins_url['path'] ) || str_starts_with( $src_url['path'], $plugins_url['path'] ) ) &&
		( ! isset( $src_url['host'] ) || ! isset( $plugins_url['host'] ) || $src_url['host'] === $plugins_url['host'] )
	) {
		// Make the src relative the specific plugin.
		if ( isset( $plugins_url['path'] ) ) {
			$relative = substr( $src_url['path'], strlen( $plugins_url['path'] ) );
		} else {
			$relative = $src_url['path'];
		}
		$relative = trim( $relative, '/' );
		$relative = explode( '/', $relative );

		$languages_path = WP_LANG_DIR . '/plugins';

		$relative = array_slice( $relative, 1 ); // Remove <plugin name>.
		$relative = implode( '/', $relative );
	} elseif ( ! isset( $src_url['host'] ) || ! isset( $site_url['host'] ) || $src_url['host'] === $site_url['host'] ) {
		if ( ! isset( $site_url['path'] ) ) {
			$relative = trim( $src_url['path'], '/' );
		} elseif ( str_starts_with( $src_url['path'], trailingslashit( $site_url['path'] ) ) ) {
			// Make the src relative to the WP root.
			$relative = substr( $src_url['path'], strlen( $site_url['path'] ) );
			$relative = trim( $relative, '/' );
		}
	}

	/**
	 * Filters the relative path of scripts used for finding translation files.
	 *
	 * @since 5.0.2
	 *
	 * @param string|false $relative The relative path of the script. False if it could not be determined.
	 * @param string       $src      The full source URL of the script.
	 */
	$relative = apply_filters( 'load_script_textdomain_relative_path', $relative, $src );

	// If the source is not from WP.
	if ( false === $relative ) {
		return load_script_translations( false, $handle, $domain );
	}

	// Translations are always based on the unminified filename.
	if ( str_ends_with( $relative, '.min.js' ) ) {
		$relative = substr( $relative, 0, -7 ) . '.js';
	}

	$md5_filename = $file_base . '-' . md5( $relative ) . '.json';

	if ( $path ) {
		$translations = load_script_translations( $path . '/' . $md5_filename, $handle, $domain );

		if ( $translations ) {
			return $translations;
		}
	}

	$translations = load_script_translations( $languages_path . '/' . $md5_filename, $handle, $domain );

	if ( $translations ) {
		return $translations;
	}

	return load_script_translations( false, $handle, $domain );
}

Hooks

apply_filters( ‘load_script_textdomain_relative_path’, string|false $relative, string $src )

Filters the relative path of scripts used for finding translation files.

Changelog

Version Description
5.1.0 The $domain parameter was made optional.
5.0.2 Uses load_script_translations() to load translation data.
5.0.0 Introduced.