Changing the language based on the language version of the user’s browser
Sometimes there is a need to change any element of the site from one language to another. This may be necessary if your site is visited by users whose language is different from the language of the site. Let’s say the site is in Romanian, but it is also visited by users from Moldova, for whom Russian is preferable.
Usually in such cases it is recommended to create a separate page with a certain language, designed for the user. But there is another option: when accessing the site, request the language version of the browser and display the text in the desired language.
So users from Romania will receive the text in Romanian, and users from Moldova in Russian.
Consider an example based on the colormag theme.
We have a block: You may like it. Let’s create conditions under which different text will be displayed for different users, depending on the language version of the browser.
Settings must be made in this file inc/related-posts.php
A line of code is responsible for the output of the text
echo get_theme_mod( 'colormag_you_may_also_like_text', esc_html__( 'You May Also Like', 'colormag' ) );
For the request regarding the language, we will use the element of the HTTP_ACCEPT_LANGUAGE array, which will give us an idea of the client’s preferences regarding the language.
Let’s create conditions:
- Romanian language
- Russian language
- all other languages.
The point all other languages is needed in order to inform the client of a language that does not fit either of the two conditions. By default it will be English.
So let’s create a script:
$lang = substr($_SERVER[‘HTTP_ACCEPT_LANGUAGE’], 0, 2);
if($lang == “ro”){
echo get_theme_mod( ‘colormag_you_may_also_like_text’, esc_html__( ‘S-ar putea să-ți placă și…’, ‘colormag’ ) );
}
elseif($lang == “ru”){
echo get_theme_mod( ‘colormag_you_may_also_like_text’, esc_html__( ‘Возможно вам понравится’, ‘colormag’ ) );
}
else{
echo get_theme_mod( ‘colormag_you_may_also_like_text’, esc_html__( ‘You May Also Like’, ‘colormag’ ) );
}
// echo get_theme_mod( ‘colormag_you_may_also_like_text’, esc_html__( ‘You May Also Like’, ‘colormag’ ) );
There you go, it’s very simple. Checking the script can be checked on this page. Depending on your preferred language, you’ll get the appropriate title text. Similarly, you can change the language of any element on your site.