One of the battles I face with plugins is explaining to people that they really do need to use wp_enqueue_scripts() for their code. And often I get an argument back that they can’t because they need to include parameters.

Hold on to your hats. You totally can.

The Misconception

It’s easy to get confused with code. There are so many different ways to solve the same problem, we get twisted around. Let’s say that you wanted to include the following script in your website:

<script src="https://mycoolsite.com/widget.js" async></script>

That’s pretty straightforward in WordPress:

wp_enqueue_script( 'my-widget', 'https://mycoolsite.com/widget.js', array( 'jquery' ), 1.0.0 );<

But. What if you wanted to add this as well:

<script type="text/javascript">
    var _widget_options = {
        theme: 'slow' // Choose from 'fast', 'stop', and 'slow'. Remove this property to get the default theme.
};
</script>

Now you clearly have to hand-code this into WordPress. Right?

Wrong!

Use Inline Scripts!

You may have heard about wp_add_inline_script before. If not, don’t feel bad. What this does is add extra, inline, code to an already enqueued script.

Which means that to add the extra code, you do this:

wp_add_inline_script( 'my-widget', 'var _widget_options = { theme: "slow" }', 'before' );

Which will echo out exactly what you need.

The cool thing about this, is what if you want your plugin to have a lot of options? Like you want to use the value for an option to determine what your script should do?

$my-widget-inline = 'var _widget_options = { theme: "' . get_option( 'my-widget-theme' ) . '" }';
wp_add_inline_script( 'my-widget', $my-widget-inline, 'before' );

And now you’ve got flexibility.

Keep In Mind…

First, the name of the script matters. If you enqueue it as ‘my-widget’ then you call it as ‘my-widget’ as the first parameter in your inline script.

Second, you can change ‘before’ to ‘after’ if you need it to be after the script.

Third, as with all things, make sure you only load your javascript when you must. No one likes a slow site because you’re loading your javascript on every page when it only needs to be on a specific custom post type.

Reader Interactions

Comments

  1. Is this better, worse or no different than using wp_localize_script()?

    In the example, is _widget_options available as a global variable to the script?

  2. @Damien Carbery: It’s ‘easier’ in my mind and more accurate to use this instead of localize. If you read https://developer.wordpress.org/reference/functions/wp_localize_script/ it’s actually there to, you know, localize 🙂 This is adding options. And yes _widget_options is a variable in the script.

%d bloggers like this: