Get the Translated Page URL for the Current Language in WPML

Anyone who has used WPML knows that it automatically translates post links and navigation links to the corresponding page in the current language. But sometimes we still need to hard-code some links in our own code. If we only use get_permalink, we get the current page’s URL, not the matching translated URL. The solution is actually very simple.

WPML language links

Add the following code to functions.php. It adds a function that retrieves the translated page. If you are familiar with WPML, you will notice that the code is built around WPML’s icl_object_id function.

function get_permalink_current_language( $post_id )
{
	$language = ICL_LANGUAGE_CODE;

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

When using it, we only need to pass the current post ID into the function.

get_permalink_current_language( $post_id )

Related Posts

Leave a Reply

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