Including scripts and styles properly

Since this has been a discussed topic over support forums and IRC this week, a very quick scripts and style guide for WordPress.

The function for including a stylesheet is wp_enqueue_style:

[php]wp_enqueue_style( $handle, $src, $deps, $ver, $media );[/php]

You can define the handle for the style (as a reference for other styles later), the location, dependent styles (when you need a style to be loaded after other styles), it’s version if needed and the type of stylesheet (all, print, screen, handheld)

Each script is included via wp_enqueue_script:

[php]wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );[/php]

The first four arguments are identical, and the last one is a boolean variable that includes the script in the header or in the footer (depending on whether the script should be loaded before the content is ready or it’s acceptable to take it’s time after)

There are 3 hooks in WordPress used for including styles and scripts at the appropriate moment of the WordPress initialization cycle:

  • wp_enqueue_scripts – add CSS files and scripts to be rendered on the frontend of the site (such as: home/front page, page/post views, CPT single views, archives, taxonomy views)
  • admin_enqueue_scripts – JavaScript and CSS files for the admin section – dashboard, listing and edit screens, custom plugin/theme options pages
  • login_enqueue_scripts – used for the login page specifically

It’s kinda odd at first to include styles at hooks with ‘scripts’ suffix, but Andrew Nacin has a post explaining the changes.

Leave a Reply

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