Search code examples
javascriptjquerywordpressjquery-ui-datepickerwpml

How to retrieve WPML current language code to use the correct date format in jQuery Datepicker?


I have this hotel wordpress site using WPML to handle the internationalization. The model I use is each language has its language folder: mysite.com/en/, mysite.com/de/, etc All is working properly.

I use a jQuery Datepicker to let visitors select a date range within a form. It works ok except for the part where I need to handle the date format.

How can the #arrivalDate and #departureDate fields use the correct date format based on the site language?

See my code below.

Here's my JS code

jQuery(document).ready(function ($) {
    // Function to retrieve the current language using WPML JavaScript API
    function getCurrentLanguage() {
        if (window.ICL_LANGUAGE_CODE) {
            return window.ICL_LANGUAGE_CODE;
        } else {
            // Fallback to browser language
            var browserLanguage = (navigator.language || navigator.userLanguage).substr(0, 2);
        return browserLanguage;
    }
}

// Get the current language and display it in HTML
var currentLanguage = getCurrentLanguage();
var languageElement = document.getElementById('current-language');
if (languageElement) {
    languageElement.textContent = currentLanguage;
}

// Define date formats based on language
var dateFormats = {
    'en': 'mm/dd/yy', // English date format
    'fr': 'dd/mm/yy', // French date format
    // Add more language-date format mappings as needed
};            

from = $( "#arrivalDate" ).datepicker({
    dateFormat: 'dd/mm/yy'  // <= I assume this is where I need to do something clever,
    defaultDate: "+1w",
    changeMonth: true,
    changeYear: true,
    showWeek: true,
    numberOfMonths: 1,
    showOn: "both",
    buttonImage: "/includes/calendar-alt-solid_red.png",
    buttonImageOnly: true,
    buttonText: "Select arrival date",
    firstDay: 1
   })
.on( "change", function() {
   to.datepicker( "option", "minDate", getDate( this )+1 ) //<= this never works, I assume this is because it doesn't know the right date format;
   }),
to = $( "#departureDate" ).datepicker({
    dateFormat: 'dd/mm/yy' // <= I assume this is where I need to do something clever,
    defaultDate: "+1w",
    changeMonth: true,
    changeYear: true,
    showWeek: true,
    numberOfMonths: 1,
    showOn: "both",
    buttonImage: "/includes/calendar-alt-solid_red.png",
    buttonImageOnly: true,
    buttonText: "Select departure date",
    firstDay: 1
  })
  .on( "change", function() {
    from.datepicker( "option", "maxDate", getDate( this ) );
  });
function getDate( element ) {
  var date;
  try {
    date = $.datepicker.parseDate( dateFormat, element.value );
  } catch( error ) {
    date = null;
  };
  return date;
}
} );

Here's the HTML part:

<form id="2023" data-toggle="validator" role="form" method="post" action="xxxxx" target="_blank" autocomplete="off">
<input type="hidden" id="language" name="language" value="en" />
<input type="text" id="arrivalDate" name="arrivalDate" autocomplete="off" placeholder="From" data-date-format="dd/mm/yyyy" data-link-field="arrival" data-link-format="dd/mm/yyyy">
<input type="text" id="departureDate" name="departureDate" autocomplete="off" placeholder="To" data-date-format="dd/mm/yyyy" data-link-field="departure" data-link-format="dd/mm/yyyy">
<button>Send</button>
</form>

I need to display the correct language value in the form and the correct date format.

I tried to build this but failed to connect the dots. I'm close but I'm not making progress here. Any guidance or documentation I could dig into?

Thank you

Greg


Solution

  • You can get the language code with php using the wpml_current_language hook and you can share it as a global variable using wp_localize_script function

    So your code might look like that:

    function my_enqueue_function(){
        $wpml_current_lang = apply_filters( 'wpml_current_language', NULL );
        wp_localize_script('my-script', 'globalVars', array(
            'currentLang'  =>     $wpml_current_lang,
        ));
    }
    add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
    

    Then you can use it inside your javascript like this (for example):

    <script>
        const lang = globalVars.currentLang
    </script>
    

    In order to get the current language.