Translation Function

If you wish to translate custom text you can do this by calling the function trp_translate($content, $language = null, $prevent_over_translation = true );.

The following parameters are used:

  • $content(required): The actual text you wish to translate. It can be any simple text or HTML.
  • $language(optional): The language you wish your content to be translated to. If you do not add this parameter the content will be translated to the current language.
  • $prevent_over_translation(optional): This parameter is used to ensure that the translated text will not be picked up by TranslatePress later on in order to attempt a second translation. It adds a wrapping <span data-no-translation> tag. This default behavior can be changed by setting $prevent_over_translation to false in which case the <span> tag will not be added. It’s safe to set it to ‘false’ if the translated text is not simply printed (echoed) in the HTML source and therefore detected by TP.

The returned value is a string containing the translated content in the initial form( text or HTML), using the translation available in DB or automatic translation if activated. The HTML structure is kept, the function translating only the node and attributes inside tags.

In the following example, we can observe the functionality of the trp_translate function:

  • in a PHP file write the following code:
  • function tpc_enqueue_scripts(){
    
        $message = trp_translate('<div>Hey, this is a test.</div><p>This is another test.</p>', 'pt_BR');
    
        $tpc_array = array();
    
        $tpc_array['alert'] = $message;
    
        echo '<button id=tpc_test_button>Click Here</button>';
    
        wp_enqueue_script( 'tpc_test_trp_translate_function', plugin_dir_url( __FILE__ ). '/assets/output.js', array("jquery"), 1.0, true );
    
        wp_localize_script( 'tpc_test_trp_translate_function', 'tpc_alert_message', $tpc_array);
    
    }
    
    add_action('wp_enqueue_scripts', 'tpc_enqueue_scripts');
  • in a javascript file write the following code:
jQuery(function() {

    jQuery( '#tpc_test_button' ).on( 'click', function () {
        alert( tpc_alert_message['alert'] );
    } );

});

The following example should append a button that clicked will show an alert box with the translated HTML:

 

Looking to go multilingual?

Get full access to TranslatePress and join 200.000+ website owners that grow their multilingual traffic.

Unlock PREMIUM Features

Or download FREE version