wp_localize_jquery_ui_datepicker()
云策文档标注
概述
wp_localize_jquery_ui_datepicker() 函数用于本地化 jQuery UI 日期选择器,使其适配 WordPress 的日期格式和本地化设置。它通过转换 PHP 日期格式为 jQuery UI 格式,并设置默认选项来实现。
关键要点
- 函数检查 jquery-ui-datepicker 脚本是否已入队,未入队则直接返回。
- 使用 str_replace() 将 WordPress 的日期格式转换为 jQuery UI 兼容的格式。
- 通过 wp_json_encode() 生成包含本地化文本、月份/星期名称、日期格式、起始星期和 RTL 设置的 JSON 数据。
- 调用 wp_add_inline_script() 将设置默认值的 JavaScript 代码添加到 jquery-ui-datepicker 脚本中。
代码示例
// 示例:函数内部核心代码片段
$datepicker_date_format = str_replace(
array('d', 'j', 'l', 'z', 'F', 'M', 'n', 'm', 'Y', 'y'),
array('dd', 'd', 'DD', 'o', 'MM', 'M', 'm', 'mm', 'yy', 'y'),
get_option('date_format')
);
$datepicker_defaults = wp_json_encode(
array(
'closeText' => __('Close'),
'currentText' => __('Today'),
'monthNames' => array_values($wp_locale->month),
'monthNamesShort' => array_values($wp_locale->month_abbrev),
'nextText' => __('Next'),
'prevText' => __('Previous'),
'dayNames' => array_values($wp_locale->weekday),
'dayNamesShort' => array_values($wp_locale->weekday_abbrev),
'dayNamesMin' => array_values($wp_locale->weekday_initial),
'dateFormat' => $datepicker_date_format,
'firstDay' => absint(get_option('start_of_week')),
'isRTL' => $wp_locale->is_rtl(),
),
JSON_HEX_TAG | JSON_UNESCAPED_SLASHES
);
wp_add_inline_script('jquery-ui-datepicker', "jQuery(function(jQuery){jQuery.datepicker.setDefaults({$datepicker_defaults});});");注意事项
- 函数依赖于全局变量 $wp_locale 和 WordPress 选项(如 date_format、start_of_week),确保这些已正确设置。
- 仅在 jquery-ui-datepicker 脚本已入队时生效,否则无操作。
- 使用 JSON_HEX_TAG 和 JSON_UNESCAPED_SLASHES 标志增强 JSON 安全性。
原文内容
Localizes the jQuery UI datepicker.
Source
function wp_localize_jquery_ui_datepicker() {
global $wp_locale;
if ( ! 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' )
);
$datepicker_defaults = wp_json_encode(
array(
'closeText' => __( 'Close' ),
'currentText' => __( 'Today' ),
'monthNames' => array_values( $wp_locale->month ),
'monthNamesShort' => array_values( $wp_locale->month_abbrev ),
'nextText' => __( 'Next' ),
'prevText' => __( 'Previous' ),
'dayNames' => array_values( $wp_locale->weekday ),
'dayNamesShort' => array_values( $wp_locale->weekday_abbrev ),
'dayNamesMin' => array_values( $wp_locale->weekday_initial ),
'dateFormat' => $datepicker_date_format,
'firstDay' => absint( get_option( 'start_of_week' ) ),
'isRTL' => $wp_locale->is_rtl(),
),
JSON_HEX_TAG | JSON_UNESCAPED_SLASHES
);
wp_add_inline_script( 'jquery-ui-datepicker', "jQuery(function(jQuery){jQuery.datepicker.setDefaults({$datepicker_defaults});});" );
}
Changelog
| Version | Description |
|---|---|
| 4.6.0 | Introduced. |