Getting the URL for a translated page based on the URL of a different language using WPML

When working with WPML the other day I ran into the following issue. I had to redirect the visitor to the preferred language translated page, based on an url. This also ment that at the point of redirecting there no post id yet know.

I wrote the following function to solve the problem described above.

function get_url_for_language( $original_url, $language )
{
	$post_id = url_to_postid( $original_url );
	$lang_post_id = icl_object_id( $post_id , 'page', true, $language );
	
	$url = "";
	if($lang_post_id != 0) {
		$url = get_permalink( $lang_post_id );
	}else {
		// No page found, it's most likely the homepage
		global $sitepress;
		$url = $sitepress->language_url( $language );
	}
	
	return $url;
}

Related Posts

Powered By Related Posts for WordPress
Click Here to Learn More About Related Posts for WordPress

6 thoughts on “Getting the URL for a translated page based on the URL of a different language using WPML

  1. Thanks!, Excellent function 😀

  2. Oh man…
    You are a savior! 🙂

  3. Thanks ! You are Great bro…

Leave a Reply

Your email address will not be published. Required fields are marked *