Anatomy Of A WordPress Plugin: Loading The JavaScript

WordPressAdditional functionality can be added to a WordPress using JavaScript. For example, the Series Index uses JavaScript to allow the index to be shown or hidden when the user clicks a toggle link. The JavaScript will be stored in a separate file which, when I use it, I usually call jquery.js and is placed in the plugin folder alongside the main plugin file.

To make use of the JavaScript, the file then needs to be loaded within the plugin. When working with procedural code, the following snippet of code from my Series Index plugin shows how the file can be loaded:

add_action('wp_enqueue_scripts', 'azc_si_load_jquery');

function azc_si_load_jquery(){
	wp_enqueue_script( 'azurecurve-series-index', plugins_url('jquery.js', __FILE__), array('jquery'), '3.9.1');

The add_action hook can be used to call a function which then calls wp_enqueue_script; this is the “safe” way of loading a script file for a WordPress plugin.

The structure of the call is:

  • handle – the first parameter is the name of the script and is mandatory.
  • source – the location of the script file and is mandatory; this should never be hard-coded as it cannot be guaranteed to be the same on every site. Using the plugins_url function the path of the current file can be automatically retrieved

    The first parameter to plugins_url is the file we want, and __FILE__ will be used to determine the folder location of the plugin file; the returned data will be the path concatenated with the filename.

  • dependencies – an array containing all of the files which must be loaded before the one being loaded here.
  • version – the script version number; used to ensure the correct script is passed to the client. This parameter is optional and if not supplied will be defaulted to the WordPress version.
  • in footer – this optional parameter controls where the script is loaded. If not supplied, the scripts are placed in the element of the HTML document. If set to true, the script is placed before the end tag; this requires the theme to have the wp_footer() template tag in the appropriate place.

By using wp_enqueue_style, the script is loaded at the right time alongside the other scripts; at the start of the post I said this was the “best” way of including scripts, but it on reflection I should have stated that this is the “correct” way of including scripts into a plugin.

Click to show/hide the Anatomy Of A WordPress Plugin Series Index

1 thought on “Anatomy Of A WordPress Plugin: Loading The JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *