Created
July 31, 2020 05:02
-
-
Save huanyichuang/e322b27dd1a211af31f1822e0c2b4ba1 to your computer and use it in GitHub Desktop.
Because the pages in the new version doesn't need to be edited (hard-coded), it seems better to use PO/MO directly for the multi-lingual website.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Language detector | |
* This global variable is used to detect the language that the user's browser is using. | |
* Should be passed to step to get the specified language's MO file. | |
*/ | |
function applemint_locale( $locale ) { | |
//Create a global variable so that other functions and hooks can use the variable to determine the language. | |
global $am_lang; | |
//Set up default lanuages that can be matched. | |
$locale_list = array( | |
'zh' => 'zh_TW', | |
'zh-hant' => 'zh_TW', | |
'ja' => 'ja', | |
); | |
//Detecting the language either with the GET variable `lang` or the browsers' default. | |
if ( isset( $_GET['lang'] ) || isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] )) { | |
$am_lang = $_GET['lang'] ?: substr( $_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2 ); | |
} else { | |
$am_lang = 'ja'; | |
} | |
//Matching the locale. | |
if ( array_key_exists( $am_lang, $locale_list ) ) { | |
$locale = $locale_list[$am_lang]; | |
} else { | |
$locale = 'ja'; | |
} | |
return $locale; | |
} | |
add_filter( 'locale', 'applemint_locale', 20, 1 ); | |
/** | |
* Language attributes transformation | |
* This is used to set up the correct zh-hant language attribute rather than zh-TW. | |
*/ | |
function applemint_lang_attr( $output, $doctype ) { | |
global $am_lang; | |
if ( preg_match( '/^zh/', $am_lang ) ){ | |
$output = preg_replace( '/lang="([\w-]+)"/', 'lang="zh-hant"', $output ); | |
} else { | |
$output = preg_replace( '/lang="([\w-]+)"/', 'lang="' . $am_lang . '"', $output ); | |
} | |
return $output; | |
} | |
add_filter( 'language_attributes', 'applemint_lang_attr', 21, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment