Last active
May 13, 2025 10:53
-
-
Save a11smiles/0d6694557a06fbffb9c5bc7425561822 to your computer and use it in GitHub Desktop.
Weglot Translation Shortcode
This file contains hidden or 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
function translate_shortcode( $atts = [], $content = null, $tag = '' ) { | |
// Get current URI and set cache timeout | |
$current_url = $_SERVER["REQUEST_URI"]; | |
$cache_timeout = 86400; | |
// normalize attribute keys, lowercase | |
$atts = array_change_key_case( (array) $atts, CASE_LOWER ); | |
// override default attributes with user attributes | |
$custom_atts = shortcode_atts( | |
array( | |
'lang' => 'en', | |
'label' => 'English', | |
), $atts | |
); | |
$o = null; | |
// Get URL from cache if possible | |
if ( false === ( $o = get_transient( get_the_guid() . '__' . $custom_atts['lang'] ) ) ) { | |
$language_services = weglot_get_service( 'Language_Service_Weglot' ); | |
$request_url_services = weglot_get_service( 'Request_Url_Service_Weglot' ); | |
if ( ! is_null($language_services) && ! is_null($request_url_services) ) { | |
//create url object | |
$wg_url = $request_url_services->create_url_object( $current_url ); | |
// get a language | |
$language = $language_services->get_language_from_internal($custom_atts['lang']); | |
//display url for language | |
$translated_url = $wg_url->getForLanguage( $language ); | |
if ( ! is_null($translated_url) ) { | |
$o = '<a href="' . $translated_url . '" class="lang-link" data-wg-notranslate>' . $custom_atts['label'] . '</a>'; | |
set_transient(get_the_guid() . '__' . $custom_atts['lang'], $o, $cache_timeout); | |
} | |
} | |
} | |
// return output | |
return $o; | |
} | |
function translate_shortcode_init() { | |
add_shortcode( 'translate', 'translate_shortcode' ); | |
} | |
add_action( 'init', 'translate_shortcode_init' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment