Last active
December 7, 2019 00:44
-
-
Save Luckyfella73/85a5dd54d482156d463199d6d19e45cd to your computer and use it in GitHub Desktop.
Timber Twig function - WPML - get translation url by passing langcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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