How to localize a script in WordPress

Before we localize a script, we need to register a script first. Because without this, we can not localize any script. Because to localize a script, we need a registered script handle.

Here is the syntax to register a script.

wp_enqueue_script( $handle:string, $src:string, $deps:array, $ver:string|boolean|null, $in_footer:boolean )

wp_enqueue_script( 'myjs', 'path_to_js_file', array( 'jquery' ), '1.0', true );

Now we have a handle for registered JavaScript. We can use that handle to localize script. Here is the syntax to localize script

wp_localize_script( $handle:string, $object_name:string, $l10n:array )

wp_localize_script(
	'myjs',
	'myjs_vars',
	array(
		'my_var_1' => 'value 1',
		'my_var_2' => 'value 2',
		'my_var_3' => 'value 3',
	)
);

Now in your JavaScript file you can call it like below.

$.ajax({
url: myjs_vars.my_var_1,
....... 
you ajax code
.......
})

Published
Categorized as Dev

Leave a comment

Your email address will not be published.