2

What's the better way to add an inline script in WordPress theme or plugin? Is it by the function wp_add_inline_script, or using the hook wp_footer? and why?

3

wp_add_inline_script() is intended to be used for inline scripts that use or depend on another script that's been enqueued with wp_enqueue_script(). It ensures that the inline script is placed appropriately relative to the main script and will won't appear if the main script is unregistered. The example from the announcement was using Typekit:

function mytheme_enqueue_typekit() {
   wp_enqueue_script( 'mytheme-typekit', 'https://use.typekit.net/<typekit-id>.js', array(), '1.0' );
   wp_add_inline_script( 'mytheme-typekit', 'try{Typekit.load({ async: true });}catch(e){}' );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_typekit' );

Which results in

<script type='text/javascript' src='https://use.typekit.net/<typekit-id>.js?ver=1.0'></script>
<script type='text/javascript'>
try{Typekit.load({ async: true });}catch(e){}
</script>

Hooking into wp_footer is perfectly fine, but if your script depends on another script being loaded first it is less reliable, because you need to manually make sure that you add it in the correct place and properly remove it if the script is dequeued so that errors don't occur.

If your script does not depend on another script, and needs to be inline, then wp_footer would be the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.