Like the blog? Get the book »

Better Way to Add Inline Scripts

Better Way to Add Inline Scripts

If you are a WordPress developer, you may have used the WordPress hook wp_print_scripts to add any necessary inline JavaScript. Alternately, you may have used the function wp_localize_script() to add your inline scripts. But did you know that not too long ago, WordPress added a new function for adding inline JavaScript? Yep, as of WordPress version 4.5 and better, we can use the superior function wp_add_inline_script() to do the job.

One of the nice things about this newer function is that you can associate it with any registered script AND include more than just JavaScript variables. This DigWP article explains how wp_add_inline_script() works, why it’s better than either of the alternate inline methods, and how to support older (pre-4.5) versions of WordPress. Along the way, we’ll look at some example code that you can customize and use in your own WordPress projects.

Inline scripts via wp_print_scripts

In the past, one way to add inline scripts to the frontend was to use the action hook wp_print_scripts (and/or admin_print_scripts for the Admin Area). Here is an example function adapted from one of my plugins:

// inline script via wp_print_scripts
function shapeSpace_print_scripts() { 
	
	?>
	
	<script>
		var var1 = <?php echo json_encode('var1'); ?>;
		var var2 = <?php echo json_encode('var2'); ?>;
		var var3 = <?php echo json_encode('var3'); ?>;
	</script>
	
	<?php
	
}
add_action('wp_print_scripts', 'shapeSpace_print_scripts');

This function defines three variables based on plugin options, and then outputs them to the head section (on the front-end) using the wp_print_scripts hook. To instead add the script to the Admin Area, we would replace wp_print_scripts with admin_print_scripts and call it a day.

Pros

Works every time to add any scripts to the <head> section of your web pages. No restriction on the code that is added; you can add JS variables, conditionals, methods, functions, or whatever you want.

Cons

No way to associate the added code with any registered script. You can sort of control the relative location of the added code using the $priority parameter of the add_action() function. But mostly the output code depends on other factors, so not any real, consistent way to control output location.

Inline scripts via wp_localize_script()

Another common way that developers include inline JavaScript is the function, wp_localize_script(). This function is meant for localizing JavaScript variables for use with internationalization and language translation. But I think a lot of developers use it just to add inline scripts. Here is an example:

// inline scripts via wp_localize_script()
function shapeSpace_enqueue_scripts() {
	
	wp_enqueue_script('shapeSpace_script', get_template_directory_uri() .'/js/script.js', array(), '1.0', true);
	
	$array = array(
		'var1' => __('Value for Variable 1', 'shapeSpace'),
		'var2' => __('Value for Variable 2', 'shapeSpace'),
		'var3' => __('Value for Variable 3', 'shapeSpace'),
	);
	
	wp_localize_script('shapeSpace_script', 'shapeSpace', $array);
	
}
add_action('wp_enqueue_scripts', 'shapeSpace_enqueue_scripts');

This example function enqueues our JavaScript file and gives it a handle/ID of shapeSpace_script. Then an associative array that contains our variables is defined. And lastly, the variables are passed to wp_localize_script() to be included inline along with the registered script, shapeSpace_script. This enables us to use any of the added JS variables like shapeSpace.var1, etc.

Pros

This technique is nice because it enables (read: requires) association with an existing/registered script. So it provides a consistent way to manage the relative location of your custom script output.

Cons

The only real downside to this otherwise robust technique is that you can only add JavaScript variables (i.e., var = 'value';). So if you need to add other types of inline scripts, like equations, conditionals, functions or whatever, it’s just not possible to do with wp_localize_script().

BEST: inline scripts via wp_add_inline_script()

Now that we’ve seen the pros and cons of the two alternate inline-script techniques, let’s look at a better way using the new(er) WordPress function, wp_add_inline_script(). In practice, it looks quite similar to wp_localize_script(), but can do a LOT more. Here is an example:

// inline scripts via wp_add_inline_script()
function shapeSpace_enqueue_scripts() {
	
	wp_enqueue_script('shapeSpace_script', get_template_directory_uri() .'/js/script.js', array(), '1.0', true);
	
	$script  = 'var1 = '. json_encode('var1') .'; ';
	$script .= 'var2 = '. json_encode('var2') .'; ';
	$script .= 'var3 = '. json_encode('var3') .'; ';
	
	wp_add_inline_script('shapeSpace_script', $script, 'before');
	
}
add_action('wp_enqueue_scripts', 'shapeSpace_enqueue_scripts');

This may not look like much, but it’s actually super awesome. We have the best of BOTH worlds:

  • add ANY JavaScript snippet
  • associate with any registered script

That means we have full control over script content and its relative location. Also note the third parameter, $position. That enables us to include the $script either before or after the $handle, shapeSpace_script.

Pro Tip: Always escape your inline JavaScript using json_encode() or equivalent.

Pros

All pros. Add literally any JavaScript code inline, located either before or after the registered script, which itself may be included in the head section or footer. So you have full control.

Cons

None. All good.

Complete Example: Inline Script with Fallback

Putting everything together, we can fashion a complete technique for adding inline scripts that works in virtually ANY version of WordPress. For example, I use the following 3-function technique in my front-end posts plugin.

// enqueue scripts
function shapeSpace_enqueue_scripts() {
	
	wp_enqueue_script('shapeSpace_script', get_template_directory_uri() .'/js/script.js', array(), '1.0', true);
	
	shapeSpace_inline_script();
	
}
add_action('wp_enqueue_scripts', 'shapeSpace_enqueue_scripts');


// inline scripts WP >= 4.5
function shapeSpace_inline_script() {
	
	$wp_version = get_bloginfo('version');
	
	if (version_compare($wp_version, '4.5', '>=')) {
		
		$script  = 'var1 = '. json_encode('var1') .'; ';
		$script .= 'var2 = '. json_encode('var2') .'; ';
		$script .= 'var3 = '. json_encode('var3') .'; ';
		
		wp_add_inline_script('shapeSpace_script', $script, 'before');
		
	}
	
}


// inline scripts WP < 4.5
function shapeSpace_print_scripts() { 
	
	$wp_version = get_bloginfo('version');
	
	if (version_compare($wp_version, '4.5', '<')) {
		
		?>
		
		<script>
			var var1 = <?php echo json_encode('var1'); ?>;
			var var2 = <?php echo json_encode('var2'); ?>;
			var var3 = <?php echo json_encode('var3'); ?>;
		</script>
		
		<?php
		
	}
	
}
add_action('wp_print_scripts', 'shapeSpace_print_scripts');

That’s the magic ticket right there. Three simple functions. First we enqueue our JavaScript file. From there, we call the second function, which adds our inline script using wp_add_inline_script() for WordPress versions 4.5 and better. Then the third and final function is the fallback for older versions of WordPress. Anything older than 4.5 will add our inline script via the wp_print_scripts hook. So bottom line is that the above technique works perfectly to add inline scripts to any version of WordPress going back to like 2.1 or something crazy.

Recap

Here is a recap just FYI. Adding inline scripts to WordPress:

  • wp_print_scripts / admin_print_scripts — Add any code to the header
  • wp_localize_script() — Add any JS variables to any registered script
  • wp_add_inline_script() — Add any JS code to any registered script

Also: Want to add inline CSS/style instead of JavaScript? WordPress provides a set of “add style” functions that are similar to those used for adding scripts. For example, check out wp_add_inline_style() and wp_print_styles.

4 responses

  1. Thank you for this great post!
    Is it possible to implement Structured Data on Woocommerce pages with this method (JSON-LD)?

    • Thanks Michael! Yes it should be possible as the techniques in the tutorial are pretty much the standard way to add scripts and styles. Not sure about Woocommerce though, never use it!

  2. Question for you Jeff. I am struggling to get some inline javascript to appear using wp_print_footer_scripts. I know you stated that’s not the ideal method, but I am trying to simply carry over legacy wordpress code in a contracted update.

    The code in question has been thoroughly tested and vetted, and it not subject to outside modification. There are many newline characters and other odd markup. Could you list the characters that would prevent wordpress from compiling javascript? Could you explain in more depth how encoding to json is a good practice?

    Many thanks–

    David

    • Hi David, honestly I’m not sure.. I haven’t used wp_print_footer_scripts in quite some time. It may be a good question to post in the WP Support Forum, gotta be someone there who can provide more information. Another idea would be to examine the function itself in the WP core, might provide some insight.

Comments are closed for this post. Contact us with any critical information.
© 2009–2024 Digging Into WordPress Powered by WordPress Monzilla Media shapeSpace