WP Localize Script



Actually, I was able to make this work, but I had to bypass Beans's asset compiler... is there any way to do this through regular bean api?


Hi Marc,

As usually, it is good to know what things do so let's look at wp_localize_script in the example below:

add_action( 'wp_enqueue_scripts', 'example_localize_script' );

function example_localize_script() {

 wp_localize_script( 'uikit', 'objectName', array(
   'objectKey' => 'ojectValue'
 ) );

}

So what does it do?

  • The first argument says to only add it if the JavaScript file uikit is enqueued (more details further down).
  • The second argument defines the JavaScript object name.
  • The 3rd argument defines the JavaScript ojbect.

So the code above would add the following in your page `` which will essentially make it accessible globally:

<script type="text/javascript">
  var objectName = {"objectKey":"ojectValue"};
</script>

So you might question is what $handle to use as the first argument. Usually wp_localize_script is used after a file that you enqueue yourself which you can indeed do and use the $handle you defined. Otherwise you can use the tag uikit like in my example which will always be there unless you completely remove UIkit 🙂

Hope that helps,


Nice, I thought this had to be linked with the JS script that needed the localized object. If we can localize using uikit handle and have access everywhere, this is fantastic!

Thanks again for your invaluable support, Thierry.

Write a reply

Login or register to write a reply, it's free!