Anatomy Of A WordPress Plugin: Loading CSS & JavaScript Together

[featured-image]In the last couple of posts in this series I’ve taken a look at using wp_enqueue_scripts to load the CSS and JavaScript files.

In those examples, the CSS and JavaScript were loaded via different functions. However, we could use add_action to call one function to load both the CSS and JavaScript.

If I were to amend the Floating Featured Image plugin to load the CSS and JavaScript in one function it would look like the following:

add_action('wp_enqueue_scripts', 'azc_ffi_load_css_and_javascript');

function azc_ffi_load_css_and_javascript(){
	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__ ) );

We use the add_action to call the azc_ffi_load_css_and_javascript function which now contains both wp_enqueue_script and wp_enqueue_style calls.

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.


Leave a Reply

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