 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));
}
});
});
});
|