Skip to content Skip to sidebar

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.

Tagged: 

This topic contains 14 replies, has 1 voice.

Last updated by danieleP-41 1 week, 6 days ago.

Assisted by: Christopher Amirian.

Author Posts
July 23, 2025 at 5:55 am #17261620

danieleP-41

None of the solutions proposed worked for me, the problem was also present in a local copy I made so I found a workaround because I had a deadline to respect.
I wrote some code in functions.php and in my custom js file to create and call an api that made me translate the urls from client side and I changed it after page is loaded.
It's a dirty solution but I needed to solve the problem fast.
This is my code:

FUNCTIONS.PHP
add_action('rest_api_init', function() {
register_rest_route('wpml/v2', '/urls', [
'methods' => 'GET',
'callback' => function(WP_REST_Request $request) {
$original_url = $request->get_param('url');
$target_lang = $request->get_param('lang');

$post_id = url_to_postid($original_url);

if ($post_id) {
$translated_id = apply_filters('wpml_object_id', $post_id, 'page', false, $target_lang);

if ($translated_id) {
return [
'original_url' => $original_url,
'url' => get_permalink($translated_id)
];
}
}

return ['error' => 'Not translatable'];
},
'permission_callback' => '__return_true'
]);
});

SCCRIPT.JS

jQuery(document).ready(function() {
const textWidgets = document.querySelectorAll('.elementor-widget-text-editor');
const currentLang = document.documentElement.lang.substring(0,2);
if(currentLang == "it") {
return;
}

textWidgets.forEach(widget => {
const links = widget.querySelectorAll('a[href]');

links.forEach(link => {
const url = new URL(link.href);

if (url.hostname === window.location.hostname && link.href.indexOf("/" + currentLang + "/") == -1) {
fetch(`/wp-json/wpml/v2/urls?url=${encodeURIComponent(url.pathname)}&lang=${currentLang}`)
.then(response => response.json())
.then(data => {
if (data.url) {
link.href = data.url;
}
})
.catch(error => console.error('Errore traduzione link:', error));
}
});
});
});