Is there a way to use wp_enqueue_script() for inline scripts?
I’m doing this because my inline script depends on another script and i would like the flexibility of inserting it after it’s loaded.
Also, It’s an inline script because i’m passing php variables into the javascript (like theme path, etc)
Thanks in advance.
Well, you have wp_localize_script(), but that’s only for passing data.
Otherwise, you can do this:
The idea is that you shouldn’t rely on your inline script being printed exactly after the script it depends on, but later.
Just don’t make it an inline script and then pass the dynamic parameters to it as variables. Otto has written a great guide on how to do this effectively.
WordPress 3.3 will also make this more powerful: https://core.trac.wordpress.org/ticket/11520
This solution is similar to @scribu’s answer, but it follows the form of
wp_enquque_script()
, and will place the script in the header if its dependencies are included in the header.Note: this uses use of anonymous functions, but for PHP versions prior to 5.3 this can be easily converted to a class.
Since WordPress 4.5 you can use wp_add_inline_script():
The better way I’ve found is using
wp_localize_script()
, as @scribu suggested.Usually, I decided to use in-line Javascript because I needed to provide some PHP variables to my script. This can be solved with
wp_localize_script()
. I’ll provide an example:You have an array
$aFoo
with some options and need to pass it to a script.Using in-line script:
Using
wp_localize_script()
:Then,
pathToScript/script.js
would be:In this way you don’t need in-line scripts nevermore.
scribu is absolutely correct. Anyway, I want to add some info:
I want my function to output a script once, no matter how often it’s called. It is a content-related function, so I cannot wait for any hooks. I used scribus infos and some reading of the WP core to come up with this:
Using this method I’m able to print an inline script once. In my case I have a function that creates a share-button and needs one script to be executed for all buttons. But only once.