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.
$aFoo = array( 'option1' => $option1Value, 'option2' => $option2Value );
Using in-line script:
<script>
var oFoo = {};
oFoo.option1 = <?php echo $aFoo['option1'] ?>;
oFoo.option2 = <?php echo $aFoo['option2'] ?>;
//do some stuff with oFoo
</script>
Using wp_localize_script()
:
wp_register_script( 'script_name', 'pathToScript/script.js', array( 'jquery' )); //if jQuery is not needed just remove the last argument.
wp_localize_script( 'script_name', 'object_name', $aFoo ); //pass 'object_name' to script.js
wp_enqueue_script( 'script_name' );
Then, pathToScript/script.js
would be:
var oFoo = {};
oFoo.option1 = object_name.option1;
oFoo.option2 = object_name.option2;
//do some stuff with oFoo (no PHP needed)
In this way you don't need in-line scripts nevermore.