Here’s a PHP snippet that you can use to return a custom link to a specific language for the current page using WPML.
<?php
function get_custom_language_link( $lang ) {
$current_url = get_permalink();
if ( function_exists( 'icl_get_home_url' ) ) {
$translated_url = apply_filters( 'wpml_permalink', $current_url, $lang );
$translated_url = str_replace( home_url(), icl_get_home_url(), $translated_url );
} else {
$translated_url = $current_url;
}
return $translated_url;
}
?>
This will output the custom link for the specified language code and can be used on any page.
<?php
$lang = 'fr';
$translated_url = get_custom_language_link( $lang );
echo $translated_url;
?>
Example 1: This will output a link that says “Switch to French” and links to the translated version of the current page in French.
<?php
$lang = 'fr'; // replace with the language code of your desired language
$translated_url = get_custom_language_link( $lang );
?>
<a href="<?php echo $translated_url; ?>">Switch to French</a>
Example 2: This will output a list of links for English and French, wrapped in an unordered list.
<?php
$en_url = get_custom_language_link( 'en' );
$fr_url = get_custom_language_link( 'fr' );
?>
<ul class="language-switcher">
<li><a href="<?php echo $en_url; ?>">EN</a></li>
<li><a href="<?php echo $fr_url; ?>">FR</a></li>
</ul>