Locale filter in conjunction with new datepicker localization

I was able to successfully change the datepicker’s strings to a different locale for a single page using the switch_to_locale() function introduced in WordPress v4.7.

switch_to_locale() will modify the global $wp_locale variable which is used by wp_localize_jquery_ui_datepicker(). Changing the locale with the locale filter alone does not overwrite $wp_locale.

/**
 * Use switch_to_locale() on a special page.
 * This needs to be done early.
 */
add_action( 'pre_get_posts', 'wpse_change_language' );
function wpse_change_language( $query ) {
    if ( $query->is_main_query() && $query->is_page( 156 ) ) {
        // This will change the global $wp_locale which
        // is used by wp_localize_jquery_ui_datepicker() for translations.
        switch_to_locale( 'fr_FR' );
    }   
}

Enqueue datepicker styles and scripts.

/**
 * Load jQuery datepicker scripts and styles.
 */
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_datepicker' );
function wpse_enqueue_datepicker() {
    wp_enqueue_script( 'jquery-ui-datepicker' );

    // Using code.jquery.com for simplicity. Normally I'd use a local file.
    wp_register_style(
        'jquery-ui',
        'https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css'
    );
    wp_enqueue_style( 'jquery-ui' );

    // A simple datepicker initialization script.
    wp_enqueue_script(
        'wpse-datepicker',
        plugin_dir_url( __FILE__ ) . '/wpse-datepicker.js',
        [ 'jquery-ui-datepicker' ],
        false,
        true
    );
}

wpse-datepicker.js

/**
 * Attach a datepicker to our markup.
 */
jQuery( document ).ready(function( $ ) {
    $( "#datepicker" ).datepicker();
});

Shortcode (for demo purposes)

/**
 * A simple shortcode used for adding the markup for
 * the datepicker.
 */
add_shortcode( 'wpse_datepicker', 'wpse_datepicker' );
function wpse_datepicker() {
    // Start buffering output.
    ob_start(); 

    // Add some debugging info:
    echo '<p>The locale is: ' . get_locale() . '</p>';
    ?>

    <div id="datepicker"></div>

    <?php
    // Return output generated up to this point.
    return ob_get_clean();
}

Content of page with ID 156

Testing the datepicker:

[wpse_datepicker]

Test complete!

Also note that it is necessary to have the language files installed for whatever locale is being used. They can be automatically installed by selecting the appropriate language in the admin area under Settings > General > Site Language.

Leave a Comment