Add the code to an external JavaScript file inside your plugin directory, then use
wp_enqueue_script()
to load it.
Here's how the call should be made:
<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ??>
Assuming you have your plugin file and js file in the same directory, your call will look something like this:
function load_my_plugins_javascript() {
wp_enqueue_script( 'script-name', plugins_url( 'script.js' , __FILE__ ) , array( 'jquery' ), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'load_my_plugins_javascript' );
This adds your loader function to the array of other functions called by
wp_enqueue_scripts()
. By passing the parameter
array( 'jquery' )
to
$deps
, you're telling WordPress to load the built-in jQuery script first, then load your custom script; this helps resolve dependency issues.
If you have your scripts in a subfolder inside your plugin, you'll want to use
dirname( __FILE__ )
in the example above. Also, I'm assuming that your script is intended to run on the front-end of the site; if you are loading the script just for the admin side, you'll need to alter that call.
The Codex is the perfect source for this info. Check out
http://codex.wordpress.org/Function_Reference/wp_enqueue_script[
^] for the syntax and examples, and
http://codex.wordpress.org/Function_Reference/plugins_url[
^] for how to get the URL to a file inside your plugin.