Home›Support›English Support›[Resolved] Switching languages on search results page it redirects to incorrect page
[Resolved] Switching languages on search results page it redirects to incorrect page
This thread is resolved. Here is a description of the problem and solution.
Problem:
When I search in Italian or English, when I click on the language selector, I do not stay on the search page. Instead, I am redirected to a product page.
Solution:
This was not caused by WPML. Custom code was used in this setup, causing a redirect
This is the technical support forum for WPML - the multilingual WordPress plugin.
Everyone can read, but only WPML clients can post here. WPML team is replying on the forum 6 days per week, 22 hours per day.
Languages: English (English )Spanish (Español )German (Deutsch )
Timezone: Europe/Madrid (GMT+02:00)
Hi,
thanks for the video. The redirect doesn't happen to me when I switch to English. Actually, nothing is happening.
I reactivated all plugins except WPML, WooCommerce, WooCommerce Multilingual and the Avada Plugins, then switching the language works, but still here without redirect: hidden link.
This comes from a 301 redirect on your installation:
That page ID referred to the "shop page", a WooCommerce page.
I deleted the page and dynamically changed the "href" value of the link in the language selector, adding a JS function.
The point is that using plugins (e.g. FiboSearch) to allow searching by SKU and only showing products as search results creates some problems with the language selector.
The JS code, added via function.php is this:
function add_custom_script() {
?>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
// Check if querystring 's' is present
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
if (!urlParams.has('s')) {
return; // If 's' is not present, stop the script
}
// Function to construct the URL based on the language
function constructUrlLanguage(baseUrl, language) {
var url = new URL(baseUrl);
var pathname = url.pathname;
// Adjust the path based on the language
if (language === 'it') {
pathname = pathname.replace('/en/', '/');
} else if (language === 'en') {
if (!pathname.includes('/en/')) {
pathname = '/en' + pathname;
}
}
url.pathname = pathname;
// Update the 'lang' parameter
url.searchParams.set('lang', language);
return url.href;
}
// Update the href for Italian
var linkIt = document.querySelector('#menu-item-wpml-ls-39-it a');
if (linkIt) {
linkIt.href = buildUrlLanguage(window.location.href, 'it');
}
// Update the href for English
var linkEn = document.querySelector('#menu-item-wpml-ls-39-en a');
if (linkEn) {
linkEn.href = buildLanguageUrl(window.location.href, 'en');
}
});
</script>
<?php
}
add_action('wp_footer', 'add_custom_script');
If anyone was in the same situation as me and if they needed it.