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.
Hi Devin,
I have purchased Portfolio+ a few months ago for my blog and I would like to use it for a second website I am starting. Do I have to purchase it again or is there a way to use the same?
thanks,
Emily
Hi Devin,
Thank you for the tutorial. It really helps. I hadn’t known yet that WP has wp_localize_script function. It’s handy to use and it helps a lot.
Mauris