I’ve been working on a plugin that needs to update the text of an object via javascript when an element is clicked. Like the rest of my plugin, those strings in the javascript need to be translatable. Thankfully WordPress makes this easy to do.
Original
Let’s say this is the script you are enqueuing:
function prefix_enqueue_custom_script(){
wp_register_script( 'prefix_custom_script', plugin_dir_url( __FILE__ ) .'js/custom-script.js', array( 'jquery' ) );
wp_enqueue_script( 'prefix_custom_script' );
}
Translatable
In this custom script there are two strings that should be translatable: “upload” and “remove”. To make this happen we’ll use the wp_localize_script function, which gets hooked onto the script handle:
function prefix_enqueue_custom_script(){
wp_register_script( 'prefix_custom_script', plugin_dir_url( __FILE__ ) .'js/custom-script.js', array( 'jquery' ) );
wp_enqueue_script( 'prefix_custom_script' );
wp_localize_script( 'prefix_custom_script', 'prefix_object_name', array(
'upload' => __( 'upload', 'textdomain' ),
'remove' => __( 'remove', 'textdomain' )
) );
}
Using the Strings
Now in my javascript, instead of simply using the text “upload” and “remove” I’ll use the variables prefix_object_name.upload and prefix_object_name.remove.