Loading Scripts in WordPress Themes and Child Themes, Quickly

Here’s how I load scripts and styles in WordPress themes, in functions.php.

function load_scripts() {
    // load styles
    wp_enqueue_style( 'custom-css-1', get_stylesheet_directory_uri() . '/css/custom-css-1.css' );
    wp_enqueue_style( 'my-secret-script-css', get_stylesheet_directory_uri() . '/css/my-secret-script.css' );


    // load javascript
    wp_enqueue_script( 'my-secret-script', get_stylesheet_directory_uri() . '/js/my-secret-script.js' );

}
add_action( 'wp_enqueue_scripts', 'load_scripts' );

The above code would load up two css files, custom-css-1.css and my-secret-script.css. It would also load one JavaScript file, my-secret-javascript.js.

This post by Brian Krogsgard at WPCandy describes the proper way of loading scripts, using wp_register_script, as it takes dependencies into consideration and allows loading of scripts by their defined name. However, I think the wp_register_script methodology is lengthier and a bit more difficult to read, mostly due to the dependency stuff.

However, you do need to take dependencies into consideration if you’re using a JavaScript library, like jQuery.

wp_register_style should also be used to load styles with dependencies. This article at Tuts+ has a very good description and examples on loading CSS stylesheets using wp_register_style and wp_enqueue_style.

You should also be aware of the differences when authoring themes and plugins, which Brian also explains in his post on WPCandy. That mostly involves one WordPress function out for another.

Let me know if you run into any issues, comments are open!