Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active January 1, 2023 23:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save igorbenic/375ec7d1a1439bab7012fe15a55c36e4 to your computer and use it in GitHub Desktop.
Save igorbenic/375ec7d1a1439bab7012fe15a55c36e4 to your computer and use it in GitHub Desktop.
How to create a Simple WordPress Language Switcher | https://www.ibenic.com/how-to-create-a-simple-wordpress-language-switcher/
<?php
// ... previous code
class SimpleWordPressLanguageSwitcher {
// ... previous code
/**
* Return the correct locale based on the $_GET parameter.
*/
public function get_locale_to_set() {
if ( isset( $_GET['locale'] ) ) {
switch ( $_GET['locale'] ) {
case 'en':
return 'en_US';
break;
case 'hr':
return 'hr';
break;
}
}
return false;
}
}
<?php
// ... previous code
class SimpleWordPressLanguageSwitcher {
// ... previous code
public function set_locale() {
if ( $this->get_locale_to_set() ) {
$locale = $this->get_locale_to_set();
setcookie( 'my_language', $locale, time() + YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
switch_to_locale( $locale ); // Switching directly just in case.
return;
}
}
}
<?php
// ... previous code
class SimpleWordPressLanguageSwitcher {
// ... previous code
public function get_locale( $locale ) {
if ( $this->get_locale_to_set() ) {
$locale = $this->get_locale_to_set();
} else {
$locale = isset( $_COOKIE['my_language'] ) ? $_COOKIE['my_language'] : $locale;
}
return $locale;
}
}
<?php
/**
* Plugin Name: Simple WordPress Language Switcher
* Version: 1.0.0.
*/
if ( ! defined( 'ABSPATH' ) ) { return; }
class SimpleWordPressLanguageSwitcher {
public function __construct() {
add_action( 'init', [ $this, 'set_locale' ] );
add_action( 'pre_determine_locale',[ $this, 'get_locale' ] );
}
/**
* Set the Locale in Cookie if it exists.
*/
public function set_locale() {
}
/**
* Get the Locale from cookie if it exists.
*/
public function get_locale( $locale ) {
return $locale;
}
}
new SimpleWordPressLanguageSwitcher();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment