Problem
When creating a customised language selector for TranslatePress
$arr = trp_custom_language_switcher();
Code language: PHP (php)
$arr returns a multi-dimensional array with all the necessary parameters to render an individual language selector within a loop.
In the frontend, however, when the foreign language was activated, the entry of the array was deleted with the key
"<span class="sf-dump-key">current_page_url</span>" => "<span class="sf-dump-str" title="32 characters">https://example.test/</span>"
Code language: HTML, XML (xml)
overwritten with
https://example.com/en
Code language: JavaScript (javascript)
The "en" doesn't belong there!
Solution
A separate snippet, where you can switch between the languages and then integrate this via ShortCode, e.g:
add_shortcode( 'mnc_lang_switcher', function ( $atts = [], $content = null, $tag = '' ) {
global $post;
if ( ! function_exists( 'trp_custom_language_switcher' ) ) {
return;
}
$arr = trp_custom_language_switcher();
$current_language = get_locale();
$s = [];
$arial_label = __( 'Sprachwähler', 'YOUR-THEME-DOMAIN' );
foreach ( $arr as $lang ) {
$url = $lang['current_page_url'];
$linktext = $lang['language_name'];
if(strtolower($linktext) === 'german') {
$linktext = 'Deutsch';
}
$class = get_locale() === $lang['language_code'] ? 'active' : '';
$s[] = sprintf('<a data-no-translation-href class="%s" href="%s">%s</a>', $class, $url, $linktext);
}
$links = implode("\n", $s);
return <<<OUT
<nav aria-label="$arial_label" class="mnc_lang_switch" data-no-translation>
$links
</nav>
OUT;
} );
Code language: PHP (php)