If you’re a theme developer, you’re probably familiar with the category.php and category-{id}.php template files. The later lets you display a single category differently.

But using category-{id}.php in practice is not that fun: firstly, you have to leave a comment in the theme file so that you know what it’s for. Secondly, you have to rename the file for each site that you use the theme on, because the category id isn’t constant.

No more: in WordPress 2.9, you’ll be able to use the category slug instead. For example: say you have a News category on your site. If you want to display it differently, you can just create this file:

category-news.php

and when a site visitor goes to /category/news, that file will be loaded.

If you don’t want to wait until 2.9 ships to use this feature, you can add this code to your theme’s functions.php file and you’re good to go:

add_filter('category_template', 'category_slug_template');
function category_slug_template($template) {
	$cat_ID = absint( get_query_var('cat') );
	$category = get_category( $cat_ID );

	if ( is_wp_error( $category ) )
 		return false;

	$new_template = locate_template(array("category-" . $category->slug . '.php'));

	if ( $new_template )
		return $new_template;

	return $template;
}

This feature was brought to you courtesy of:

  • Tim Schoffelman, who started the discussion on the wp-hackers mailing list
  • myself, who opened a ticket with a patch
  • Peter Westwood, who commited the patch

Happy theming!