Translatable Javascript Strings

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.

About Devin

I am a developer based in Austin, Texas. I run a little theme shop called DevPress and help manage a WooCommerce shop with Universal Yums. Find me on twitter @devinsays.

2 Responses

  1. 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

Leave a Reply