If you are like me, you often want to control what template file WordPress uses. Some of the methods I’ve seen around the internet try to use template_redirect. Others are even worse and employ sticking tons of conditionals inside WordPress template files (eg category.php).
Well I am here to tell you there is a much easier way. It’s fairly unknown and sparsely documented. It’s the template_include filter.
The use cases for template_include are endless but I will give you a great example where I recently took advantage of it.
Let’s say you have a category structure like below:
Looks straight forward, right? Using the normal WordPress template hierarchy you can easily target these categories. We all know category-news.php would be used when viewing the News category or category-health.php would take care of the Health category.
However, what if you want to create a unique template for all the News sub-categories? Here are the two options you will usually find.
- Create a category.php file and use conditionals to target the individual sub categories. Lame!
- Create a template file for each sub-category (category-local.php, category-health.php, etc). Even more lame!
I want to have one template file that will be used for all the News sub-categories, not conditionals or duplicate scattered everywhere. With single snippet (which would be in functions.php) using the template_include filter this can be done!
The code above first checks to see if you are looking at a category. If that is true it then checks to see if the parent category ID is 7. Finally, if this checks out it uses a template file I created, subcategory-news.php.
Pretty easy, right?
Props to @wpmuguru for sending me in this direction.