I am trying to: use this 'wpml_object_id' hook to get translated page. it works on experiment but not on hidden link. Here, sometimes it fetches the correct page id and sometimes it doesn't. Are there any settings that might be missing
Link to a page where the issue can be seen: hidden link
I expected to see: hidden link
Instead, I got: hidden link
Here is the code snippet where I am using this hook.
function redirect_mexico_users() {
if (strpos($_SERVER['REQUEST_URI'], 'es-mx') !== false) {
return; // Exit the function if the user is already on the Spanish page
}
$is_mx =isset($_SERVER['GEOIP_COUNTRY_CODE']) && $_SERVER['GEOIP_COUNTRY_CODE'] === 'MX';
if ( ($is_mx && !isset($_COOKIE['user_preference'])) || ($is_mx && (isset($_COOKIE['user_preference']) && $_COOKIE['user_preference'] === 'MX'))){
// Check if the spanish page exists against the default languages's page ID
$default_lang_path = trim( home_url().$_SERVER['REQUEST_URI'], '/');
$default_lang_page_id = url_to_postid($default_lang_path);
$spanish_page_id = apply_filters('wpml_object_id', $default_lang_page_id, 'page', false, 'es-mx');
Languages: English (English )German (Deutsch )French (Français )
Timezone: Europe/Zagreb (GMT+02:00)
Hi,
Thank you for contacting WPML support!
Given that it works sometimes, can you disable caching and see if that is where the issue is coming from? Caching plugins or server-side caching could interfere with dynamic functions. Ensure that caching is disabled for the pages where this redirection logic is applied, or clear the cache after making changes.
You could also test this by hardcoding a known page ID and test if the redirection works reliably, something like:
function redirect_mexico_users() {
if (strpos($_SERVER['REQUEST_URI'], 'es-mx') !== false) {
return;
}
$is_mx = isset($_SERVER['GEOIP_COUNTRY_CODE']) && $_SERVER['GEOIP_COUNTRY_CODE'] === 'MX';
if ($is_mx) {
$default_lang_page_id = 123; // Replace with a known page ID
$spanish_page_id = apply_filters('wpml_object_id', $default_lang_page_id, 'page', false, 'es-mx');
if ($spanish_page_id) {
$url = home_url() . "/es-mx" . $_SERVER['REQUEST_URI'];
wp_redirect($url);
exit;
}
}
}
add_action('wp', 'redirect_mexico_users');
Thanks for your response. I'll try that but just curious that my experiment environment also uses same server side cache. But I don't see any such issue there. Why so?