如何获取WPML当前语言代码以适配jQuery Datepicker日期格式
WPML多语言站jQuery Datepicker适配方案
1. 根据当前语言自动适配日期格式
WPML提供了直接获取当前语言的函数,我们可以通过PHP将语言对应的日期格式传递到前端JS,实现自动适配:
步骤1:在主题functions.php中注册脚本并传递语言配置
function load_datepicker_with_lang_support() { // 加载jQuery UI Datepicker基础资源(若主题未内置) wp_enqueue_script('jquery-ui-datepicker'); wp_enqueue_style('jquery-ui-base', '//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css'); // 获取WPML当前语言标识 $current_lang = icl_get_current_language(); // 定义各语言对应的日期格式(可按需扩展) $lang_date_formats = [ 'en' => 'mm/dd/yy', 'de' => 'dd.mm.yy', 'fr' => 'dd/mm/yy', 'es' => 'dd/mm/yy', 'it' => 'dd/mm/yy' ]; // 把配置传递给前端JS wp_localize_script( 'jquery-ui-datepicker', 'datepickerLangConfig', [ 'format' => $lang_date_formats[$current_lang] ?? 'mm/dd/yy' ] ); // 加载自定义Datepicker逻辑脚本 wp_enqueue_script( 'hotel-datepicker', get_template_directory_uri() . '/js/hotel-datepicker.js', ['jquery', 'jquery-ui-datepicker'], '1.0', true ); } add_action('wp_enqueue_scripts', 'load_datepicker_with_lang_support');
2. 修复日期范围联动功能
利用jQuery Datepicker的onSelect事件,实现到达/离开日期的双向联动限制:
步骤2:编写JS逻辑(hotel-datepicker.js)
jQuery(document).ready(function($) { // 初始化到达日期选择器 const $arrival = $('#arrivalDate').datepicker({ dateFormat: datepickerLangConfig.format, minDate: 0, // 禁止选择过去日期 onSelect: function(selectedArrival) { // 计算离开日期的最小可选值:到达日期+1天 const minDeparture = new Date(selectedArrival); minDeparture.setDate(minDeparture.getDate() + 1); $departure.datepicker('option', 'minDate', minDeparture); } }); // 初始化离开日期选择器 const $departure = $('#departureDate').datepicker({ dateFormat: datepickerLangConfig.format, onSelect: function(selectedDeparture) { // 计算到达日期的最大可选值:离开日期-1天 const maxArrival = new Date(selectedDeparture); maxArrival.setDate(maxArrival.getDate() - 1); $arrival.datepicker('option', 'maxDate', maxArrival); } }); // 处理页面加载时已有初始值的情况(比如回显表单数据) const initialArrival = $arrival.val(); if (initialArrival) { const minDeparture = new Date(initialArrival); minDeparture.setDate(minDeparture.getDate() + 1); $departure.datepicker('option', 'minDate', minDeparture); } const initialDeparture = $departure.val(); if (initialDeparture) { const maxArrival = new Date(initialDeparture); maxArrival.setDate(maxArrival.getDate() - 1); $arrival.datepicker('option', 'maxDate', maxArrival); } });
关键注意事项
- 若主题已加载jQuery UI,可移除
wp_enqueue_script('jquery-ui-datepicker')避免重复加载; - 日期格式可根据语言习惯调整,比如德语可改为
dd.mm.yy,法语用dd/mm/yy; - 若出现JS冲突,可通过浏览器开发者工具的Console面板排查错误,优先确保jQuery未被重复加载;
- 测试时需切换不同语言目录(如
/en/、/de/)验证格式是否自动切换,联动逻辑是否生效。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

