WordPress: the proper way to include javascripts and stylesheets

It’s easy to add javascripts and stylesheets to HTML pages, eg

<head>
....
<link rel="stylesheet" href="mystyle.css" />
<script src="myscript.js"></script>
....
</head>

However in WordPress, whether developing themes or plugins, the proper way is to enqueue scripts and stylesheets to avoid any problems, such as duplicates and version incompatibilities.

The following examples shows how this can be done in a WordPress theme.

Include JavaScript

Instead adding the above codes in header.php, simply add a few codes to functions.php:

add_filter('wp_enqueue_scripts', 'theme_load_scripts');
function theme_load_scripts() {
    wp_enqueue_script('myscript',
        get_template_directory_uri() . '/myscript.js',
        array('jquery'),
       '1.0', 
       true);
    
}

note:

  • the above codes adds the scripts tag to the html page
  • line 3: ‘myscript’ is the handle that can be referenced and the name must be unique.
  • line 4: full path to the script.
  • line 5: optional. specify that the script requires jQuery. WordPress comes with jQuery script and will add it before adding myscript.js
  • line 6: optional. the script’s version.
  • line 7: optional. true to put in the footer instead in <head>.

Check out functions wp_enqueue_script() and wp_register_script() for further details on how to do this.

Include stylesheets

In functions.php:

add_filter('wp_enqueue_scripts', 'theme_load_styles');
function theme_load_styles() {
    wp_enqueue_style('mystyle',
        get_template_directory_uri() . '/mystyle.css',
        '',
       '1.0');
    
    // conditional stylesheet, eg for versions before IE9
    globals $wp_styles;
    wp_register_style('for-ie', get_template_directory_uri() . '/ie.css');
    $wp_styles->add_data('for-ie', 'conditional', 'IE');
    wp_enqueue_style('for-ie');
}

notes line 9-12: this adds conditional tags for IE browsers.

Check out wp_enqueue_style() and wp_register_style() for further detail.

Conditional

Note that as of WordPress v3.4, you still can’t conditionally enqueue JavaScript. The only fix is to add the code in template.

1 thought on “WordPress: the proper way to include javascripts and stylesheets

  1. Priednis Reply

    Hi,
    I had to use wp_register_script before I could use wp_enqueue_script on my script. Using wordpress 3.5
    This should be mentioned somewhere in the article. Otherwise thanks for the tip!

Leave a Reply

Your email address will not be published. Required fields are marked *