I am integrating a wordpress site with another site. The integration consists of a form hosted in wordpress that the user fills out and submits to the other site. I’m using a custom page template which includes several jquery plugins for things like form validation, etc. Currently I’m linking directly to the js files in the template eg.
<script src="/join/js/jquery.validate-1.11.1.min.js"></script>
Is there a recommended directory for storing javascript files like this? Right now they are in a directory I created in the wordpress root. Is there a recommended way to include jquery plugins? What is the advantage of using wp_enqueue_script(‘jquery.validate….js’) instead of linking directly?
Why you shouldn’t hardcode javascript files
There are several reasons why you shouldn’t hardcode links to javascript files:
wp_register_script()
) you are then free to usewp_enqueue_script()
in any widgets, shortcodes or templates. Better still, the script is only enqueued if the appropriate tempate, widget or shortcode is used: impossible if its hardcoded.wp_register_script()
/wp_enqueue_script()
allows you or other plug-ins to make use ofwp_localize_script()
(originally intended for passing localised strings, but more widely used for passing options stored in the database which can then be used in your javascript files.Where to store the javascript files?
There’s no set location to store javascript files (in your plug-in/theme). I tend to put them in a folder name
js
orassets/js
. Something that makes sense.How to load javascript files
First check that the jQuery plug-in (or any javascript library for that matter) isn’t already included in WordPress itself. (There’s a list here: http://codex.wordpress.org/Function_Reference/wp_register_script#Handles_and_Their_Script_Paths_Registered_by_WordPress). If it’s there, use that.
Never use your own copy of a javascript library/plug-in which is included in core. Doing so will probably break your and others’ plug-ins.
It usually makes sense to register and enqueue your script separately:
and then call
wp_enqueue_script('my-script-handle')
whenever you require the javascript file to be loaded (e.g. in a function responsible for a widget or shortcode).The advantage of this is clear: your scripts are registered in one, easily maintained place, and divorced form the the business of queuing the script which can take place ‘on the fly’ and possibly subject to some contorted logic.