What is the best way to link to a CSS file in WordPress?
Method 1: Use the following whenever needed
<link href="<?php echo get_template_directory_uri(); ?>/my-style.css" rel="stylesheet" type="text/css" />
Method 2: Use enqueue as follows
add_action('wp_enqueue_scripts', 'load_my_style');
function load_my_style () {
wp_register_style('my-style', get_template_directory_uri() . '/my-style.css');
wp_enqueue_style('my-style');
}
Please also let me know why a certain method is better than the other.
Thanks.
EDIT
And for style.css, should I use method 1 or method 2?
Method 2
controlling where the stylesheets load by means of template
conditionals, which is convenient and prevents a lot of mess in your
<head>
.example.
and replaced.
handling. See the third parameter of
wp_enqueue_style
orwp_register_style
. That means that you can register a dozenfiles and if you assign dependencies correctly you can load them all
with a single
wp_enqueue_style('my-style');
.deal but convenient.
again, not a big deal but convenient.
you cannot if you write the code into the template– for example
(and as already mentioned) some plugins compress and combine
stylesheets which is very nice if you have a lot of plugins all
loading stylesheets.
I would count #1, #2, and #4 as the biggest benefits but #3 is very important if you build themes for public consumption that might become a parent, and important if you are trying to build a child.
The recomendation is always register and enqueue scripts and styles. A lot of problems will be avoid, mainly duplicate files, diferent versions of the same script being loaded, etc. Anyway, in the case of using your very own custom css file used only in the header.php of your theme is quite rare that you get problems by not enqueue it But it is safer if you do.
You don’t want to hardcode anything. Enqueueing is the best practice and in addition, you can load it whenever you want as well. You can register it and not enqueue it until you need to.
Registering provides a way for WP to know a certain stylesheet or script is present and may be used later.
In addition, by using register/enqueue 3rd party plugins/child themes have a chance to manipulate that without modifying the core.