Skip to content

Instantly share code, notes, and snippets.

@EvanHerman
Created January 24, 2016 16:56
Show Gist options
  • Save EvanHerman/9c9f6b0374e04fe66d72 to your computer and use it in GitHub Desktop.
Save EvanHerman/9c9f6b0374e04fe66d72 to your computer and use it in GitHub Desktop.
Localize the jquery datepicker in WordPress using the WP_Locale object
<?php
add_action( 'admin_enqueue_scripts', 'admin_print_js' );
public function admin_print_js() {
global $wp_locale;
//add the jQuery UI elements shipped with WP
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'jquery-ui-datepicker' );
//add our instantiator js
wp_enqueue_script( 'myplugin-admin', MYPLUGIN_URI . "js/myplugin-admin.js", array( 'jquery-ui-datepicker' ) );
//localize our js
$aryArgs = array(
'closeText' => __( 'Done', UNIQUE_TEXT_DOMAIN ),
'currentText' => __( 'Today', UNIQUE_TEXT_DOMAIN ),
'monthNames' => strip_array_indices( $wp_locale->month ),
'monthNamesShort' => strip_array_indices( $wp_locale->month_abbrev ),
'monthStatus' => __( 'Show a different month', UNIQUE_TEXT_DOMAIN ),
'dayNames' => strip_array_indices( $wp_locale->weekday ),
'dayNamesShort' => strip_array_indices( $wp_locale->weekday_abbrev ),
'dayNamesMin' => strip_array_indices( $wp_locale->weekday_initial ),
// set the date format to match the WP general date settings
'dateFormat' => date_format_php_to_js( get_option( 'date_format' ) ),
// get the start of week from WP general setting
'firstDay' => get_option( 'start_of_week' ),
// is Right to left language? default is false
'isRTL' => $wp_locale->is_rtl(),
);
// Pass the localized array to the enqueued JS
wp_localize_script( 'myplugin-admin', 'objectL10n', $aryArgs );
}
/**
* Format array for the datepicker
*
* WordPress stores the locale information in an array with a alphanumeric index, and
* the datepicker wants a numerical index. This function replaces the index with a number
*/
function strip_array_indices( $ArrayToStrip ) {
foreach( $ArrayToStrip as $objArrayItem) {
$NewArray[] = $objArrayItem;
}
return( $NewArray );
}
/**
* Convert the php date format string to a js date format
*/
function date_format_php_to_js( $sFormat ) {
switch( $sFormat ) {
//Predefined WP date formats
case 'F j, Y':
return( 'MM dd, yy' );
break;
case 'Y/m/d':
return( 'yy/mm/dd' );
break;
case 'm/d/Y':
return( 'mm/dd/yy' );
break;
case 'd/m/Y':
return( 'dd/mm/yy' );
break;
}
}
jQuery('.datepicker').datepicker({
// Show the 'close' and 'today' buttons
showButtonPanel: true,
closeText: objectL10n.closeText,
currentText: objectL10n.currentText,
monthNames: objectL10n.monthNames,
monthNamesShort: objectL10n.monthNamesShort,
dayNames: objectL10n.dayNames,
dayNamesShort: objectL10n.dayNamesShort,
dayNamesMin: objectL10n.dayNamesMin,
dateFormat: objectL10n.dateFormat,
firstDay: objectL10n.firstDay,
isRTL: objectL10n.isRTL,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment