Search code examples
wordpresswpml

WPML get translated content of a string from all languages if available


Using WPML, I have translated a string in 4 languages say: en, nl, fr and de.

By default I can use <?php _e('my string here','text_domain'); ?> and it will return the exact translated text when I am in that domain.

How can I get all the translated texts in one place. So If I am on english version of the website but I would like to get the translated content for my string in nl, fr, de and en.

May I know how is that possible?


Solution

  • You could temporary change the current language to retrieve the translated string. Something like:

    // Backup the current language
    $current_lang = $sitepress->get_current_language();  // Say it's "en"
    
    // Switch to another language. E.g. $desired_lang = "nl";
    $sitepress->switch_lang( $desired_lang );
    
    // Get your translated string...
    _e( 'My string here', 'text_domain' );
    
    // Back to the original language to not interfere
    $sitepress->switch_lang( $current_lang );
    

    I've tested this on a page template (say index.php) and it works... Then I tried to build a function to do the job. Something like:

    // Put this in your functions.php
    function get_all_translations( $string, $languages ) {
    
        global $sitepress;
    
        if ( empty( $languages ) ) {
            $languages = array_keys(
                icl_get_languages( 'skip_missing=0&orderby=code&order=asc' )
            );
        }
    
        $current_lang = $sitepress->get_current_language();
    
        $translations = [];
        foreach ( $languages as $lang ) {
            $sitepress->switch_lang( $lang, true );
            $translations[$lang] = __( $string, 'text_domain' );
        }
    
        $sitepress->switch_lang( $current_lang );
        return $translations;
    }
    

    And:

    // This on index.php:
    var_dump( get_all_translations( 'My string here' ) );
    var_dump( get_all_translations( 'My string here', ['nl', 'fr'] ) );
    

    But it doesn't work and I can't figure out the reason... I hope this helps anyway.