wp_enqueue_script( 'azurecurve-series-index', plugins_url('jquery.js', __FILE__), array('jquery') );
wp_enqueue_style( 'azurecurve-floating-featured-image', plugins_url( 'style.css', __FILE__ ) );
This isn’t necessary, as we could continue using separate add_action calls, but it does reduce the number of calls to wp_enqueue_scripts and the number lines of code required without adding any real complexity.
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.