Switch the Front-End Language With ?lang=
Lets visitors switch the theme and plugin interface language with a ?lang=fr_FR link; the choice is remembered in a cookie and limited to languages you allow.
Opens WPIDE on
Code
$wpide_allowed = array( 'en_US', 'fr_FR', 'de_DE', 'es_ES' ); // Installed locales visitors may pick.
add_filter( 'determine_locale', function ( $locale ) use ( $wpide_allowed ) {
if ( is_admin() ) {
return $locale;
}
$pick = '';
if ( isset( $_GET['lang'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
$pick = sanitize_text_field( wp_unslash( $_GET['lang'] ) ); // phpcs:ignore WordPress.Security.NonceVerification
} elseif ( isset( $_COOKIE['wpide_lang'] ) ) {
$pick = sanitize_text_field( wp_unslash( $_COOKIE['wpide_lang'] ) );
}
return in_array( $pick, $wpide_allowed, true ) ? $pick : $locale;
}, 20 );
add_action( 'init', function () use ( $wpide_allowed ) {
if ( is_admin() || ! isset( $_GET['lang'] ) || headers_sent() ) { // phpcs:ignore WordPress.Security.NonceVerification
return;
}
$pick = sanitize_text_field( wp_unslash( $_GET['lang'] ) ); // phpcs:ignore WordPress.Security.NonceVerification
if ( in_array( $pick, $wpide_allowed, true ) ) {
setcookie( 'wpide_lang', $pick, time() + YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
}
} );
Notes
Only switches interface strings that have installed translations, not your post content. Install the languages in Settings > General first.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.