WordPress在加载主题之前加载默认的已翻译字符串functions.php
文件(see wp-settings.php#L394
). 然后locale
过滤器不再影响jQuery UI datepicker本地化。
对于@DaveRomsey和@FrankpValentynowicz的答案,我想补充一些改进:
1. Using switch_to_locale()
:
如果特定语言环境存在于全局语言的可用语言中,则此方法适用于该语言环境$wp_locale_switcher
(参见WP_Locale_Switcher#L78
).
自从WP_Locale_Switcher
使用get_available_languages()
要检索可用语言,如果fr_FR
以前没有下载过,我们必须将其下载到WP_LANG_DIR
切换到it之前:
function wpse268774_change_language($query) {
if ( $query->is_page(156) && $query->is_main_query() ) {
if (!function_exists(\'wp_download_language_pack\')) {
require ABSPATH . \'wp-admin/includes/file.php\';
require ABSPATH . \'wp-admin/includes/translation-install.php\';
$downloaded = wp_download_language_pack(\'fr_FR\');
if ($downloaded) {
switch_to_locale(\'fr_FR\');
} else {
// Maybe do something...
}
}
}
}
add_action( \'pre_get_posts\', \'wpse268774_change_language\' );
Pros:
您可以对整个页面使用标准翻译,而无需手动翻译任何内容Cons:
因为我们必须下载语言包并重新加载整个翻译的字符串,所以性能受到了很大的影响我建议您使用pre_get_posts
钩住$query->{method}
. is_page()
单独使用可能不起作用。您不应该使用页面ID,因为导入时可能会更改页面ID。
2. Using $.datepicker.setDefaults( options )
:
WordPress不使用中的语言jQuery UI Project 所以$.datepicker.setDefaults(jQuery.datepicker.regional["fr"])
方法不起作用。必须手动本地化默认选项。
我们结帐吧wp_localize_jquery_ui_datepicker()
添加到的函数wp_enqueue_scripts
挂钩(参见default-filters.php#L435
). 现在,我们必须做:
remove_action(\'wp_enqueue_scripts\', \'wp_localize_jquery_ui_datepicker\', 1000);
function wpse268774_localize_jquery_ui_datepciker() {
global $wp_locale;
if ( !is_page(156) || !wp_script_is( \'jquery-ui-datepicker\', \'enqueued\' ) ) {
return;
}
// Convert the PHP date format into jQuery UI\'s format.
$datepicker_date_format = str_replace(
array(
\'d\', \'j\', \'l\', \'z\', // Day.
\'F\', \'M\', \'n\', \'m\', // Month.
\'Y\', \'y\' // Year.
),
array(
\'dd\', \'d\', \'DD\', \'o\',
\'MM\', \'M\', \'m\', \'mm\',
\'yy\', \'y\'
),
get_option( \'date_format\' )
);
// Got this string by switching to fr_FR.
$datepicker_defaults = \'{"closeText":"Fermer","currentText":"Aujourd\\u2019hui","monthNames":["janvier","f\\u00e9vrier","mars","avril","mai","juin","juillet","ao\\u00fbt","septembre","octobre","novembre","d\\u00e9cembre"],"monthNamesShort":["Jan","F\\u00e9v","Mar","Avr","Mai","Juin","Juil","Ao\\u00fbt","Sep","Oct","Nov","D\\u00e9c"],"nextText":"Suivant","prevText":"Pr\\u00e9c\\u00e9dent","dayNames":["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],"dayNamesShort":["dim","lun","mar","mer","jeu","ven","sam"],"dayNamesMin":["D","L","M","M","J","V","S"],"dateFormat":"MM d, yy","firstDay":1,"isRTL":false}\';
wp_add_inline_script( \'jquery-ui-datepicker\', "jQuery(document).ready(function(jQuery){jQuery.datepicker.setDefaults({$datepicker_defaults});});" );
}
add_action(\'wp_enqueue_scripts\', \'wpse268774_localize_jquery_ui_datepciker\', 10, 0);
Pros:
无性能命中Cons:
仅本地化jQuery UI日期选择器选项。无法翻译页面中的其他字符串您可能需要手动转换jQuery UI日期选择器选项