To enqueue or not to enqueue

What is the best way to link to a CSS file in WordPress?

Method 1: Use the following whenever needed

Read More
<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?

Related posts

3 comments

  1. Method 2

    1. You can enqueue all of your stylesheets form the same place even
      controlling where the stylesheets load by means of template
      conditionals, which is convenient and prevents a lot of mess in your <head>.
    2. You can remove enqueued stylesheets if you need to via a plugin, for
      example.
    3. Enqueued stylesheets are child theme friendly as they can be removed
      and replaced.
    4. The style registration/enqueueing system has built in dependency
      handling. See the third parameter of wp_enqueue_style or
      wp_register_style. That means that you can register a dozen
      files and if you assign dependencies correctly you can load them all
      with a single wp_enqueue_style('my-style');.
    5. There is “version” handling via the fourth parameter– not a big
      deal but convenient.
    6. There is also built in “media” handling via the fifth parameter–
      again, not a big deal but convenient.
    7. Plugins or other code can manipulate enqueued stylesheets in ways
      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.

  2. 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.

  3. 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.

Comments are closed.