Anatomy Of A WordPress Plugin: Loading The CSS

WordPressThe majority of the plugins I have created have created have an output visible to the user. For example, the Posts Archive can be used in a widget (see the side menu) or on a page. And to display the output to the best advantage it needs to be formatted; while this can be done using inline styles it is better done using an external stylesheet (or CSS file).

To use an external stylesheet, create the .css file, which I typically call style.css, in the plugin folder next to the main php file (you can put it in a sub-folder should you wish).

This file then needs to be loaded within the plugin. When working with procedural code, the following snippet of code from my Floating Featured Image plugin shows how the file can be loaded:


add_action('wp_enqueue_scripts', 'azc_ffi_load_css');

function azc_ffi_load_css(){
	wp_enqueue_style( 'azurecurve-floating-featured-image', plugins_url( 'style.css', __FILE__ ), '', '1.0.0' );
}

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

The structure of the call is:

  • handle – the first parameter is the name of the style and is mandatory.
  • source – the location of the stylesheet 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 style sheet version number; used to ensure the correct stylesheet is passed to the client
  • media – optional string specifying the media for which this stylesheet has been defined, such as ‘screen’, ‘handheld’ or ‘print’. See this list for the full range of valid CSS-media-types. If not otherwise set will default to ‘all’

By using wp_enqueue_style, the stylesheet is loaded at the right time alongside the other stylesheets.

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