API for including stylesheets and javascript

Currently, how do you include stylesheets and javascript into your theme or theme framework? I can think of two common ways:

  1. inserting the <link> or <script> tag directly into the header.php
  2. encapsulate the <link> or <script> tags into a function that hooks into an action hook (located in header.php)

I’m not particularly happy with any of those methods. WordPress has built-in functions for dealing with these file types: wp_enqueue_style & wp_enqueue_script respectively. The only drawback with css is that the old way of @importing stylesheets is deprecated. Of course this might be a good thing, depending on whether your big on performance or not.

Anyway, I decided to build an API around those functions that would easily allow theme authors to include css and javascript into their theme—the smart way. Simply filter the global array containing all the enqueued CSS files (or javascripts), and append your own:

add_filter( 'enqueue_styles', 'my_stylesheets' );
function my_stylesheets( $styles ) {
	$styles[] = array(
		'handle' => '2col',
		'src' => MEDIA . '/layouts/2col-r.css',
	);
	return $styles;
}

I’ve outdone myself. Instead of filtering the global array like I mentioned in the previous paragraph, simply make this call in your custom-functions.php:

framework_add_stylesheet( 'master', 'master.css', 'reset.css' );
framework_add_script( 'superfish', 'superfish.js', 'jquery', true, false );

The functions automatically search the media directory in their respective locations (which can be overwritten if necessary). Removing a stylesheet or javascript is even simpler:

framework_remove_stylesheet( 'master' );
framework_remove_script( 'superfish' );

Full documentation on these functions are in the Media API docs

The API accepts up to 5 parameters, with the first two being required. The parameters are dealt with exactly like their respective functions, so check those codex links for more info on that. Once I finish testing this API, it will be available in the next release.

2 Comments

  1. RZN8
    July 13th, 2009 at 7:53 pm | Permalink

    I tried this and it is absolutely not working. I copied and pasted the code from the media api “add script specifically and when I refresh the site it gives me a white page and wordpress fails to load anything.

    Reply
  2. Forum
    July 15th, 2009 at 4:15 pm | Permalink

    Thanks a lot.

    Reply

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Download WP Framework

Discuss WP Framework

Stop by the forums and get help with your customizations!

    It Seem There Is Something Wrong With BBLD Configuration, Please Check It.

WP Framework on Twitter!

Follow WP Framework and stay in the loop on WP Framework happenings!