Wp_localize_script best practices?

Been trying to make some data accessible to scripts.min.js but when I do it in custom.php I don’t see my object anywhere. Is scripts.php really the only (and best) place to do this? Not sure if it makes a difference but I’m localizing after an if statement checks to see if a user is logged in. Thanks for any pointers.

Should be working from any of the files included with functions.php, including custom.php. Don’t forget to tell WordPress to include your code in the header or footer.

function testo() { ?>
    <script>
        alert('Custom.php!')
    </script>
<?php }

add_action('wp_footer', 'testo');
//or
add_action('wp_head', 'testo');

@cfx did you find a way to add server data to main.js via custom.php (or anything outside of scripts.php:wp_localize_script())?

I’ve always inlined it like @willthemoor suggested, but I still wonder if there’s a better way.

Yes, it turns out that wp_localize_script() needs to be called [immediately?] after the script you’re localizing for gets enqueued. This means editing lib/scripts.php.

I add a call to wp_localize_script() on all new projects (some folks didn’t want this included in the repo ultimately) so here are my last few lines of lib/scripts.php:

  wp_enqueue_script('roots_js', get_template_directory_uri() . $assets['js'], array(), null, true);
  wp_localize_script('roots_js', 'local', apply_filters('roots_localize_script', array()));
}
add_action('wp_enqueue_scripts', 'roots_scripts', 100000);

Also note that the action’s priority is changed.

Now any time I want to localize anything I just use the roots_localize_script filter and append to the array.

It can probably be cleaned up a bit but it gets the job done.

Hope that helps.

2 Likes

Pretty interesting way to accomplish it, thanks @cfx

This sounds like a great way to solve the issue.

Would you mind giving a usage example?

I’m trying to set this up and when I run this code from extras.php:

add_filter( 'roots_localize_script', array( 'foobar' ) );

I get this warning - http://d.pr/i/14t3D/5f6vTvp5

And my console.log( local ) within the _main.js results in null.

So I think I must be doing something wrong here.

Try something like this:

function localize_foobar($localize) {
  $localize['foobar'] = "Hello foobar!";
  return $localize;
}
add_filter('roots_localize_script', 'localize_foobar');

Then console.log(local.foobar); should output Hello foobar!.

2 Likes

That worked perfectly, Thanks! :slight_smile:

i get “Uncaught ReferenceError: local is not defined” when I try this

i figured it out. using latest roots/sage i did this:

in extras.php

function localize_foobar($localize) {
$localize[‘foobar’] = “Hello foobar!”;
return $localize;
}
add_filter(‘roots_localize_script’, NAMESPACE . ‘\localize_foobar’);

then in setup.php add this to the end off the assets() function:

wp_localize_script(‘sage/js’, ‘local’, apply_filters(‘roots_localize_script’, array()));