Peter Mumford’s WordPress Dev Blog

Problem Solving for Website Owners and Designers

—by a guy who loves WordPress. And I also love Jekyll. This blog is made with Jekyll. Its hosted at my Github account.

I live in Somerville, MA.

I like to sail boats, play chess, and read novels.


Assigning Templates to Categories

April 4, 2015

WordPress has an odd way of handling category templates. You are supposed to create a file called category-wildlife.php for the ‘wildlife’ category. While that is intuitive and simple, suppose you have 50 categories on your site, and 3 category layouts?

You want to be able to edit a category, and assign it a template from your list of three choices. That’s how page templates work. You certainly don’t want 50 template files for your 50 categories.

Here is the way to do it:

  1. Use Advanced Custom Fields to put a custom field named ‘template’ on your categories. I made radio button fields, with one button corresponding to each category template that I’m using: standard, sorted and tabbed. I set standard as a default field.

  2. Create three category templates: category-standard.php, category-sorted.php, category-tabbed.php.

  3. Make a template redirect to load the correct template depending on the value of the template field. Paste it into your functions file.

<?php function category_template_redirect() {
	if(is_category()) {
		$this_cat = get_the_category();
		$template_field = get_field('template', $this_cat[0]);
		if (have_posts()) {
			include(TEMPLATEPATH . '/category-' . $template_field . '.php');
		} else {
			$wp_query->is_404 = true;
add_action( 'template_redirect', 'category_template_redirect' );