In WordPress one can easily create a template file for a specific category by appending the category ID to the file name. For example, to create a template file for a category with the ID 5, we would create…
category-5.php
…in the template directory. When displaying this category WordPress will automatically load this file to render the list of posts in the category. If this file is not found WordPress will try to use category.php, then archive.php and failing to find any of these files it will use index.php. More on this can be found in the WordPress Codex.
I regularly run into a particular problem with this approach. It quite often happens that the database of a local copy of WordPress on which I am developing and that of a live site become out of sync. The categories and their IDs no longer match up and I can no longer just upload new category files to my live site and expect them to work.
Luckily there is a very simple solution to this problem. All I needed to be able to do was the ability to create a category file that I could call by name. To do this I create a filter that checks if an appropriately named file exists, and if it does, loads it.
Here is my code:
1 2 3 4 5 6 7 8 9 | add_filter('category_template','my_category_by_name'); function my_category_by_name($template){ $CatID = absint( get_query_var('cat') ); $NewFile = TEMPLATEPATH.'/category-' .sanitize_title_with_dashes(get_cat_name($CatID)).'.php'; return (file_exists($NewFile)) ? $NewFile : $template; } |
If you find my code useful, or if you know how to improve it please drop me a note or leave a comment.
Author: Diaan Mynhardt
Tags: category, filter, slug, wordpress

[...] solution is an easy one, and closely related to my Category Template by Slug solution, but this time the credit will have to go to Nathan Rice and Austin [...]
Great tip! THANKS!
I was having a lot of problems with WordPress 2.9.2 and tried to use the plugins “Idealien Category Enhancements” and “Category Templates” to get a template by category but it wasnt working.
Thanks again for this tip, this is really the simplest solution!