Categories
Intermediate

Making Life Easier with wp_localize_script

wp_localize_script is a great way to face recurring challenges.We often need to enqueue a script that relies on data from the server (i.e. the database).

For example, say we want our script to store a list of all site category Ids in a variable. One way to do this would be to include a script tag in our HTML and then echo the data as a return value for a function as shown below:

// some HTML
<script>
function getCats(){
return '<?php echo json_encode(get_cat_ids())?>';
}
</script>
// some more HTML

But this method has many drawbacks. Firstly, we may not have any HTML that we want included. Secondly, we would need to add these types of functions for all kinds of data (trust me, I’ve been through it). 

This is exactly what wp_localize_script solves. Look at this alternative solution:

/ First I'm enqueuing a script, notice the handle of the script is "my_cool_script"
wp_enqueue_script( 'my_cool_script',plugins_url( 'js/my_cool_script.js' , __FILE__ )  ,array(), 1.0, true );
// Now I'm using wp_localize_scipt
wp_localize_script( 'my_cool_script', 'coolScriptData',  
   [
		'cat_ids' => get_cat_ids(),
   ] 
);

WordPress will now create a coolScriptData object which I can use inside my script directly.

Any comments? Thoughts? let me know in the comments.


Leave a Reply

Your email address will not be published. Required fields are marked *