get_available_languages()
云策文档标注
概述
get_available_languages() 函数用于基于指定目录中的 *.mo 和 *.l10n.php 文件获取所有可用语言代码。默认目录为 WP_LANG_DIR,返回语言代码数组或空数组。
关键要点
- 函数扫描指定目录中的 *.mo 和 *.l10n.php 文件,提取语言代码(通过去除文件扩展名)。
- 参数 $dir 可选,默认为 WP_LANG_DIR;若为 null,则使用默认目录。
- 返回 string[] 类型数组,包含语言代码,若无语言文件则返回空数组。
- 内部使用 WP_Textdomain_Registry::get_language_files_from_path() 获取文件列表,并过滤掉特定前缀文件(如 continents-cities、ms-、admin-)。
- 结果可通过 'get_available_languages' 过滤器进行自定义修改。
代码示例
function get_available_languages( $dir = null ) {
global $wp_textdomain_registry;
$languages = array();
$path = is_null( $dir ) ? WP_LANG_DIR : $dir;
$lang_files = $wp_textdomain_registry->get_language_files_from_path( $path );
if ( $lang_files ) {
foreach ( $lang_files as $lang_file ) {
$lang_file = basename( $lang_file, '.mo' );
$lang_file = basename( $lang_file, '.l10n.php' );
if ( ! str_starts_with( $lang_file, 'continents-cities' ) && ! str_starts_with( $lang_file, 'ms-' ) &&
! str_starts_with( $lang_file, 'admin-' ) ) {
$languages[] = $lang_file;
}
}
}
return apply_filters( 'get_available_languages', array_unique( $languages ), $dir );
}注意事项
- 函数在 WordPress 3.0.0 中引入,4.7.0 版本添加了过滤器,6.5.0 版本改进了缓存机制并支持 *.l10n.php 文件。
- 语言代码基于文件名生成,需确保文件命名符合规范。
- 过滤器 'get_available_languages' 允许开发者修改返回的语言列表。
原文内容
Gets all available languages based on the presence of *.mo and *.l10n.php files in a given directory.
Description
The default directory is WP_LANG_DIR.
Parameters
$dirstringoptional-
A directory to search for language files.
Default WP_LANG_DIR.Default:
null
Source
function get_available_languages( $dir = null ) {
global $wp_textdomain_registry;
$languages = array();
$path = is_null( $dir ) ? WP_LANG_DIR : $dir;
$lang_files = $wp_textdomain_registry->get_language_files_from_path( $path );
if ( $lang_files ) {
foreach ( $lang_files as $lang_file ) {
$lang_file = basename( $lang_file, '.mo' );
$lang_file = basename( $lang_file, '.l10n.php' );
if ( ! str_starts_with( $lang_file, 'continents-cities' ) && ! str_starts_with( $lang_file, 'ms-' ) &&
! str_starts_with( $lang_file, 'admin-' ) ) {
$languages[] = $lang_file;
}
}
}
/**
* Filters the list of available language codes.
*
* @since 4.7.0
*
* @param string[] $languages An array of available language codes.
* @param string $dir The directory where the language files were found.
*/
return apply_filters( 'get_available_languages', array_unique( $languages ), $dir );
}
Hooks
- apply_filters( ‘get_available_languages’, string[] $languages, string $dir )
-
Filters the list of available language codes.
Changelog
| Version | Description |
|---|---|
| 6.5.0 | The initial file list is now cached and also takes into account *.l10n.php files. |
| 4.7.0 | The results are now filterable with the ‘get_available_languages’ filter. |
| 3.0.0 | Introduced. |