Use a different single template per category in WordPress

In a recent WordPress project the posts are displayed on different pages differentiated by category instead of type. In this case different designs are loaded based on categories as well, since the theme needs to match the design of the current page. WordPress does not provide a build in mechanism to do this, it only does for post types.

The solution is rather simple, use the single.php file to first check the category and load the matching template. Since in my development environment the categories might match to different IDs than in the deployed instance it’s more practical to match by name instead of ID. Importantly first the category ID needs identification by name, and is stored to load the matching template, since matching via the $post variable can only be achieved via ID not name or slug. For anybody interested I put example code up on github.

https://gist.github.com/1272148.js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s