How to Enqueue Styles

This article will show you how to safely insert your CSS for your WordPress plugin or theme into the HEAD section of both the WordPress front-end and administration panel.

I wrote an article a while back which explained how to safely enqueue JavaScript files into WordPress for your WordPress plugin or theme without simply injecting code into the HEAD section of either your the WordPress front-end or administration panel. Enqueuing scripts safely solves conflicts by preventing the same library/script from being loaded into WordPress twice.

Enqueuing your CSS into WordPress using the wp_enqueue_style function doesn’t focus as much on conflict as it simply allows a quick, efficient way of ensuring that your styles are loaded in the correct order. When you enqueue WordPress a CSS file, you may specify dependencies which tells WordPress that your CSS depends on another CSS file and should be loaded afterwards.

So where should you put this code? You can execute wp_enqueue_style when your plugin or theme file is loaded. For plugins, you can put it anywhere inside your main plugin file so that WordPress will execute wp_enqueue_style when your plugin is noticed/read initially. For a WordPress theme, you can execute wp_enqueue_style in your functions.php file.

Using wp_enqueue_style

<?php wp_enqueue_style($handle, $source, $dependencies, $version, $media); ?>

Example wp_enqueue_style

<?php wp_enqueue_style(‘mystyles’, ‘/wp-content/plugins/myplugin/style.css’, <a href="http://www.php.net/array">array</a>(‘otherstyles’, ‘morestyles’), ’1.0′, ‘screen’); ?>

wp_enqueue_style Parameters

$handle

Name of the stylesheet. This should be a unique string.

$source

The absolute path to the stylesheet relevant to your WordPress root.

$dependencies

An array of other enqueued styles that this style depends on. The array should contain the $handlevalues of the other stylesheets. If your stylesheet doesn’t have any dependencies, set this variable to false.

$version

The version of your WordPress stylesheet.

$media

This defaults to false. You may specify the CSS media type here such as “all“, “screen“, “handheld“, “print“, etc.

Revisions

There are no revisions for this post.

Tags: ,

No comments yet.

Leave a Reply