WordPress has enqueuing system which provides programmable way of loading styles. It has a built-in support for dependency management.

Example:

function custom_styles() {
	wp_register_style(
		'my_stylesheet', 
		plugins_url('my-stylesheet.css', __FILE__),
		array('bootstrap-main'), 
		'1.0', 
		'screen');
	wp_enqueue_style('my_stylesheet');
}

add_action( 'wp_enqueue_scripts', 'custom_styles' );  

We need to register a stylesheet to be enqueued by using a wp_register_style function. This function accepts 5 parameters:

  1. $handle – Handle is the unique name of your stylesheet.
  2. $src – The location of your stylesheet.
  3. $deps – An array of registered stylesheet handles this style depends on.
  4. $ver – This is the version number of your stylesheet. This parameter is optional.
  5. $media – The media for which this stylesheet has been purposed. Accepts media types- like ‘all’, ‘print’, ‘screen’ and ‘speech’ or media queries – like ‘(orientation: portrait)’ and ‘(min-width: 480px)’. This parameter is optional and its default value is ‘all’.

In the example above, we register a stylesheet with my_stylesheet name, which is located into the plugins folder and has a my_stylesheet.css filename. It is dependant on Bootstrap. The stylesheet has a version number of 1.0 and is used for computer screens, tablets, smart-phones etc.

After providing all the parameters in wp_register_style, we just call the script in wp_enqueue_style() which enqueues it.

The last step is to use the wp_enqueue_scripts action hook to actually load the style. Despite its name, it is used for enqueuing both scripts and styles in the front-end.

Was this article helpful?