Patterns for Using Theme Styles and Scripts

I’m bundling more functionality into my WordPress themes instead of into plugins these days. The best way I’ve found to handle extra scripts and styles is to use the functions wp_register_script, wp_enqueue_script, wp_register_style and wp_enqueue_style. These functions are used to setup the scripts and styles we’ll be using for our site. By sticking to these functions, WordPress will include these in the HTML when wp_head() is called, usually inside our header.php file.

We want to use these functions in our theme’s functions.php file — WordPress automatically includes this file when the theme is active even in admin mode. Here’s the start of my functions.php file:

if( !defined( 'WP_THEME_URL' ) )
  define( 'WP_THEME_URL', get_stylesheet_directory_uri() );

Now we can use an easy syntax for declaring our theme’s extra scripts and styles. Here’s an example of including a script that depends on jquery:

  // scripts
  wp_register_script( 'my-script' , WP_THEME_URL . '/my-script.js', array( 'jquery' ) );
  wp_enqueue_script( 'my-script' );

And here’s a style:

  // styles
  wp_register_style( 'my-style', WP_THEME_URL . '/my-style.css' );
  wp_enqueue_style( 'my-style' );

In fact, I usually use this method to have the required style.css file included in the header in the correct order w.r.t. other scripts that it may depend on. This keeps my header.php clean.

  wp_register_style( 'style-css', get_stylesheet_uri() );
  wp_enqueue_style( 'style-css' );

You don’t need to register a style in order to later enqueue it; enqueue can handle it all by itself, but this makes it easy to optionally include scripts and styles only when they’re needed.

For example, if you only wanted a script to be included when the user is viewing a page (not a post or the home page), you can skip the enqueue step, but add it conditionally:

if( is_page() ) 
  wp_enqueue_script( 'my-script' );

Happy WordPress Hacking! 🙂

 

Leave a Reply