what does WordPress wp_localize_script do?

can someone explain me what wp_localize_script() do?
I don’t understand what it does in the first place even I have read it in the WP Codex.

Related posts

Leave a Reply

1 comment

  1. It lets you use PHP data in the client by printing out a JavaScript object. From the Codex:

    Localizes a script, but only if script has already been added. Can
    also be used to include arbitrary Javascript data in a page.

    You use like so:

    // Register script as per Codex instructions.
    // It doesn't have to contain anything but the file must exist
    wp_register_script('handle', get_template_directory_uri() .'/js/dummy.js');
    
    // Send data to client
    wp_localize_script('handle', 'Data', array(
      'url' => home_url(),
    ));
    

    This will print an object in JavaScript:

    <script type='text/javascript'>
    /* <![CDATA[ */
    var Data = {"url":"http://..."};
    /* ]]> */
    </script>
    

    Now in the client you can access that data:

    console.log(Data.url);
    

    It’s very useful when you’re building plugins so you can separate your client from your server logic instead of mixing JS and PHP all in the same file.