Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Luckyfella73/85a5dd54d482156d463199d6d19e45cd to your computer and use it in GitHub Desktop.
Save Luckyfella73/85a5dd54d482156d463199d6d19e45cd to your computer and use it in GitHub Desktop.
Timber Twig function - WPML - get translation url by passing langcode
<?php
function add_twig_function() {
function get_translation_url_by_langcode($target_langcode) {
// docs: https://wpml.org/documentation/getting-started-guide/language-setup/custom-language-switcher/
if ( function_exists('icl_get_languages') ) {
$langlist = icl_get_languages();
$url = '';
foreach ($langlist as $item) {
if ($item['language_code'] == $target_langcode ) {
$url .= $item['url'];
}
}
return $url;
} else {
return '#wpml-plugin-needs-to-be-active';
}
}
add_filter( 'timber/twig', function( \Twig_Environment $twig ) {
$twig->addFunction( new Timber\Twig_Function( 'get_translation_url_by_langcode', 'get_translation_url_by_langcode' ) );
return $twig;
} );
}
/* returned data from `icl_get_languages()` in each array item (example):
[id] => 27
[active] => 0
[native_name] => Svenska
[missing] => 0
[translated_name] => Svenska
[language_code] => sv
[country_flag_url] => http://yourdomain/wpmlpath/res/flags/sv.png
[url] => http://yourdomain/sv/active-page-slug
*/
# In Twig-template use like this: <a href="{{ get_translation_url_by_langcode(target_langcode) }}">{{ label }}</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment