MKDO - WPML Language Switcher
<?php
/**
* Language Selector
*
* @package textdomain
*/
// Check WPML exist.
if ( function_exists( 'icl_get_languages' ) ) {
// Get the languages.
$languages = icl_get_languages( 'skip_missing=0' );
// Proceed if more than one language.
if ( count( $languages ) > 1 ) {
// Unique ID for this instance of the
// template part.
$unique = uniqid();
?>
<label for="js-language-switcher-<?php echo esc_attr( $unique ); ?>" class="sr-only">
<?php esc_html_e( 'Select Language', 'textdomain' ); ?>
</label>
<select id="js-language-switcher-<?php echo esc_attr( $unique ); ?>" class="js-language-switcher" data-current-lang="<?php echo esc_attr( ICL_LANGUAGE_CODE ); ?>"style="width: 100%">
<?php
// Output an option for each language, complete with
// with the value set to the destination URL, as well
// as the language code and flag URL as data attributes.
foreach ( $languages as $l ) {
echo '<option value="' . esc_attr( $l['language_code'] ) . '" ';
echo ( '1' === $l['active'] ) ? 'selected ': '';
echo 'data-lang-flag="' . esc_url( $l['country_flag_url'] ) . '">';
echo esc_attr( $l['translated_name'] );
echo '</option>';
}
?>
</select>
<?php
}
}
jQuery(function($) {
// select2 - Language Switcher
// -------------------------------------
var $langSwitcher = $('.js-language-switcher');
// If we have any language switchers
// on the page, proceed.
if ( $langSwitcher.length > 0 ) {
// Utility function to format the
// select2 results.
function formatLang (lang) {
if ( !lang.id ) {
return lang.text;
}
var flag = lang.element.getAttribute('data-lang-flag');
var $lang = $(
'<span><img src="' + flag + '" class="language-switcher--flag" /> ' + lang.text + '</span>'
);
return $lang;
};
// Initialise select2 for each instance
// of the switcher on the page.
$langSwitcher.each(function(i, el) {
// Pass the language in for select2.
var selectedLangCode = $(this).find(':selected').val();
// Init.
$(this).select2({
language: selectedLangCode,
minimumResultsForSearch: Infinity,
templateResult: formatLang,
templateSelection: formatLang,
});
});
// Redirect to the URL on select.
$langSwitcher.on('select2:select', function (e) {
// Retrieve the current language code.
var currentLang = $(this).attr('data-current-lang');
// Get the current location.
var currentLocation = window.location.href;
// Carry out the string replacement to give us
// the new location URL for target language.
var newLocation = currentLocation.replace( '/' + currentLang + '/', '/' + $(this).val() + '/' );
// Carry out the re-direction.
window.location.href = newLocation;
});
}
}(jQuery));