2 notes regarding your own answer:
- try to not access on super global variables directly, but using
filter_input
- your code throw a notice if
$_GET['lang']
is not set
So your code can be improved:
function toscho_change_language() {
return 'bn_BD';
}
if ( filter_input( INPUT_GET, 'lang', FILTER_SANITIZE_STRING ) === 'bn' ) {
add_filter( 'locale', 'toscho_change_language' );
}
Or if your server has PHP 5.3+
if ( filter_input( INPUT_GET, 'lang', FILTER_SANITIZE_STRING ) === 'bn' ) {
add_filter( 'locale', function() { return 'bn_BD'; } );
}
Finally, if you mind that in future you may want to support additional languages, you can write the function in a easily extensible way:
function gm_change_language( $locale ) {
$langs = array(
'bn' => 'bn_BD',
'sw' => 'sw_TZ' // Tanzania Swahili
);
$l = strtolower( filter_input( INPUT_GET, 'lang', FILTER_SANITIZE_STRING ) );
return $l && array_key_exists( $l, $langs ) ? $langs[$l] : $locale;
}
add_filter( 'locale', 'gm_change_language' );
Problem with this code is that clicking an inner link, language parameter is lost. A possible solution is to use a cookie to store the language.
I'll apply this improvement to last snippet, but can be used also in the previous.
function gm_change_language( $locale ) {
$langs = array(
'bn' => 'bn_BD',
'sw' => 'sw_TZ' // Tanzania Swahili
);
$l = filter_input( INPUT_GET, 'lang', FILTER_SANITIZE_STRING );
if ( ! empty( $l ) ) {
setcookie ( 'my_theme_lang', $l, 0 );
} else {
$l = filter_input( INPUT_COOKIE, 'my_theme_lang', FILTER_SANITIZE_STRING );
}
return $l && array_key_exists( $l, $langs ) ? $langs[$l] : $locale;
}
add_filter( 'locale', 'gm_change_language' );
And sure, as you said, you need to translate your theme and load the texdomain using load_theme_textdomain
.
And, just a note for future readers, to be able to translate strings in a theme, all of them must be wrote using i18n functions.
get_query_var
for variables that are not query variables. Use:toscho_change_language( $locale ) { $bn = filter_input( INPUT_GET, 'bn' ) ? : $locale; }
no need of get_query_var, no need of isset, just one line effective function. Regarding the 2 questions, it seems ok to me, but to be honest locale is not a field where I'm expert.