Site icon CodeRevolution Knowledge Base

How to make translatable JavaScript strings on your WordPress theme – CodeRevolution

Do you know that WordPress have a function called wp_localize_script(), which allow you to localize JavaScript strings? Here’s a practical example on how to use this little known but very useful function.

Simply paste the following code into your function.php file, where you generally enqueue scripts and styles. Line 4 shows how to use the wp_localize_script() function.

 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' ) 	) ); } 

Thanks to Devin for this code!

Exit mobile version