Skip to content

Instantly share code, notes, and snippets.

@evtihii
Created July 13, 2023 10:37
Show Gist options
  • Save evtihii/763350bcf2460e647d21767f1cb94e3f to your computer and use it in GitHub Desktop.
Save evtihii/763350bcf2460e647d21767f1cb94e3f to your computer and use it in GitHub Desktop.
Translatepress custom language switcher shortcode
<?php
/*
* Custom language switcher shortcode
*/
function trpc_language_switcher($atts)
{
ob_start();
global $TRP_LANGUAGE;
$trp = TRP_Translate_Press::get_trp_instance();
$trp_languages = $trp->get_component('languages');
$trp_settings = $trp->get_component('settings');
$settings = $trp_settings->get_settings();
$url_converter = $trp->get_component('url_converter');
if (current_user_can(apply_filters('trp_translating_capability', 'manage_options'))) {
$languages_to_display = $settings['translation-languages'];
} else {
$languages_to_display = $settings['publish-languages'];
}
$published_languages = $trp_languages->get_language_names($languages_to_display);
$current_language = array();
$other_languages = array();
$other_languages_with_flags = array();
foreach ($published_languages as $code => $name) {
if ($code == $TRP_LANGUAGE) {
$current_language['code'] = $code;
$current_language['name'] = $name;
$flags_path = apply_filters('trp_flags_path', TRP_PLUGIN_URL . 'assets/images/flags/', $code);
$flag_file_name = $code . '.png';
$flag_file_name = apply_filters('trp_flag_file_name', $flag_file_name, $code);
$current_language['flag'] = esc_url($flags_path . $flag_file_name);
} else {
$flags_path = apply_filters('trp_flags_path', TRP_PLUGIN_URL . 'assets/images/flags/', $code);
$flag_file_name = $code . '.png';
$flag_file_name = apply_filters('trp_flag_file_name', $flag_file_name, $code);
$other_languages['name'] = $name;
$other_languages['code'] = $code;
$other_languages['flag'] = esc_url($flags_path . $flag_file_name);
array_push($other_languages_with_flags, $other_languages);
}
}
?>
<div class="language" data-no-translation>
<div class="language-current" title="<?php echo esc_attr($current_language['name']); ?>" onclick="event.preventDefault()">
<img class="language-image" src="<?php echo $current_language['flag'] ?>" alt="<?php echo $current_language['name']; ?>">
<div class="language-submenu">
<?php foreach ($other_languages_with_flags as $item) { ?>
<a class="language-item" href="<?php echo esc_url($url_converter->get_url_for_language($item['code'], false)); ?>" title="<?php echo esc_attr($name); ?>">
<img class="language-image" src="<?php echo $item['flag'] ?>" alt="<?php echo $item['name']; ?>">
<?php echo $item['name']; ?>
</a>
<?php } ?>
</div>
</div>
</div>
<?php
return ob_get_clean();
}
add_shortcode('custom-language-switcher', 'trpc_language_switcher');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment