mwtsn
6/16/2017 - 8:02 AM

Dynamically Change Locale

Dynamically Change Locale

<?php
/**
 * Load default text domain
 *
 * If default WordPress Core translations don't work, add this to your
 * `functions.php` file.
 */
load_default_textdomain();
<?php
/**
 * Redefine the sites Locale (site langauge)
 *
 * In this example we try to get the country and the langauge from the page meta,
 * if that doesnt exist we fallback to the country and langauge set in the customizer,
 * which in turn fall back to gb and en.
 */
function mwtsn_example_redefine_locale( $locale ) {

    $country = get_post_meta( get_the_id(), '_mwtsn_example_global_country_override', true );
    $lang    = get_post_meta( get_the_id(), '_mwtsn_example_global_language_override', true );

    if ( ( empty( $lang ) || ! ( is_page() || is_single() || is_singular() ) ) ) {
        $country = get_theme_mod( 'mwtsn_example_multilingual_country', 'gb' );
        $lang    = get_theme_mod( 'mwtsn_example_multilingual_language', 'en' );
    }

    if ( 'default' !== $country ) {
        $locale = $lang . '_' . strtoupper( $country );
    } else {
        $locale = $lang . '-' . $country;
    }

    return $locale;

}
add_filter( 'locale', 'mwtsn_example_redefine_locale', 10 );