Skip to content

Instantly share code, notes, and snippets.

@priscillamc
Last active October 4, 2019 14:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save priscillamc/cec352556848e229f194bae0815b0864 to your computer and use it in GitHub Desktop.
Save priscillamc/cec352556848e229f194bae0815b0864 to your computer and use it in GitHub Desktop.
Adding inline javascript in WordPress 4.5+ using wp_add_inline_script()

Adding Inline Scripts in WordPress

Since WordPress 4.5, you can add the inline JavaScript using the wp_add_inline_script() function. This can be used instead of echoing inline scripts using wp_footer. The first argument is the handle of a registered script, in this case 'pretty-photo'.

function add_styles_scripts(){
	// Add script in the footer
	wp_enqueue_script('pretty-photo', get_stylesheet_directory_uri() . '/.../jquery.prettyPhoto.js', 
		array('jquery'), NULL, true);
	
	// Initialize prettyPhoto
	$inline_js = 'jQuery(function($){ $("a[rel^=\'prettyPhoto\']").prettyPhoto(); });';
	wp_add_inline_script('pretty-photo', $inline_js);
}
add_action('wp_enqueue_scripts', 'add_styles_scripts');

In the HTML, the inline script will appear in the footer after the 'pretty-photo' script by default.

<script type='text/javascript' src='http://.../jquery.prettyPhoto.js'></script>
<script type='text/javascript'>
jQuery(function($){ $("a[rel^='prettyPhoto']").prettyPhoto(); });
</script>
@rosell-dk
Copy link

Notice that wp_add_inline_script is only available from Wordpress 4.5 and up.

I do this in one of my plugins:

if (function_exists('wp_add_inline_script')) {
    // wp_add_inline_script is available from Wordpress 4.5
    wp_add_inline_script('webp-express-options-page', 'window.webpExpressPaths = ' . json_encode(Paths::getUrlsAndPathsForTheJavascript()) . ';');
} else {
    echo '<script>window.webpExpressPaths = ' . json_encode(Paths::getUrlsAndPathsForTheJavascript()) . ';</script>';
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment