函数文档

wp_get_available_translations()

💡 云策文档标注

概述

wp_get_available_translations() 函数用于从 WordPress.org API 获取可用的翻译列表,返回一个以语言代码为键的数组。如果 API 响应错误,则返回空数组。

关键要点

  • 函数返回一个数组,键为语言代码,值为包含翻译数据的关联数组,如语言代码、版本、更新日期、英文名、本地名、下载包 URL、ISO 代码数组和安装过程字符串数组。
  • 函数会优先从站点瞬态缓存中获取翻译数据,若未命中则调用 translations_api() 从 API 获取,并缓存结果 3 小时。
  • 在非安装模式下,函数会缓存数据以提高性能;在安装模式下,则跳过缓存直接获取最新数据。

代码示例

require_once( ABSPATH . 'wp-admin/includes/translation-install.php' );
$language_list = wp_get_available_translations();

注意事项

  • 调用此函数前,必须包含 translation-install.php 文件,否则可能导致致命错误,提示函数未定义。
  • 函数依赖于 translations_api() 和 WordPress 版本信息,确保相关函数和文件可用。

📄 原文内容

Get available translations from the WordPress.org API.

Description

See also

Return

array Array of translations keyed by the language code, each an associative array of data.
If the API response results in an error, an empty array will be returned.

  • ...$0 array
    • language string
      Language code.
    • version string
      WordPress version.
    • updated string
      Date the translation was last updated, in MySQL datetime format.
    • english_name string
      English name of the language.
    • native_name string
      Native name of the language.
    • package string
      URL to download the translation package.
    • iso string[]
      Array of ISO language codes.
    • strings array
      Array of translated strings used in the installation process.

Source

function wp_get_available_translations() {
	if ( ! wp_installing() ) {
		$translations = get_site_transient( 'available_translations' );
		if ( false !== $translations ) {
			return $translations;
		}
	}

	$api = translations_api( 'core', array( 'version' => wp_get_wp_version() ) );

	if ( is_wp_error( $api ) || empty( $api['translations'] ) ) {
		return array();
	}

	$translations = array();
	// Key the array with the language code.
	foreach ( $api['translations'] as $translation ) {
		$translations[ $translation['language'] ] = $translation;
	}

	if ( ! defined( 'WP_INSTALLING' ) ) {
		set_site_transient( 'available_translations', $translations, 3 * HOUR_IN_SECONDS );
	}

	return $translations;
}

Changelog

Version Description
4.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Before calling wp_get_available_translations you should include translation-install.php like in the following example:

    require_once( ABSPATH . 'wp-admin/includes/translation-install.php' );
    $language_list = wp_get_available_translations();

    Otherwise you might get this fatal error if that file was not included before:
    Fatal error: Call to undefined function wp_get_available_translations()

You must log in before being able to contribute a note or feedback.