'WPML - How to redirect non translated content to English and not to default language
I have a website where the default language is set to Italian. English is the only other language of the site. I need to redirect all other language to english and let users choose italian as well.
'm trying to use the following code but it has some problem. It doesn't work in certain cases when the referer is not empty while entering the page for the first time. Can someone point me on the right direction?
/*
* WPML browser redirect fix.
*
*/
function wpml_browser_redirect_fix()
{
global $sitepress, $post;
$browser_language_code = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$active_languages = $sitepress->get_active_languages();
$reffered = @$_SERVER['HTTP_REFERER'];
if (!array_key_exists($browser_language_code, $active_languages)) {
$language_code = 'en';
if (!$reffered) {
if (is_home() || is_front_page()) {
if ($sitepress->get_current_language() != $language_code) {
wp_redirect($sitepress->convert_url(site_url(), $language_code));
}
} else {
if ($post->ID) {
if ($sitepress->get_current_language() != $language_code) {
$post_type = get_post_type($post->ID);
wp_redirect(get_permalink(icl_object_id($post->ID, $post_type, true, $language_code)));
}
}
}
}
} else {
foreach ($active_languages as $language_code => $language) {
if ($browser_language_code == $language_code && !$reffered) {
if (is_home() || is_front_page()) {
if ($sitepress->get_current_language() != $language_code) {
wp_redirect($sitepress->convert_url(site_url(), $browser_language_code));
}
} else {
if ($post->ID) {
if ($sitepress->get_current_language() != $language_code) {
$post_type = get_post_type($post->ID);
wp_redirect(get_permalink(icl_object_id($post->ID, $post_type, true, $language_code)));
}
}
}
}
}
}
}
add_action('wp_head', 'wpml_browser_redirect_fix', 0);
Solution 1:[1]
A possible alternative, without using code: you can try to change the default language to English - if that's an option. That's in WPML > Languages > Site Languages > Change default language.
Then in WPML > Settings > Post Types Translation, set the 'post' and 'page' post types to Translatable: use translation if available or fallback to default language.
That way any missing post/page in Italian should redirect to English.
As always, it's a good idea to create a site backup before you start modifying things, just in case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | montrealist |
