The WordPress template hierarchy is an amazing miracle of programming that seems to hold all of the answers in terms of making a WordPress theme. It is very rare when I encounter an issue where I don’t want to let the Template Hierarchy do what it is meant to do, but I have encountered such instances.
The Use Case:
I created a new Custom Post Type to built a knowledge base with WordPress. This CPT was very much separate from the default “posts” since we used the posts for blogging and news and the knowledge base for a very specific set of resources, downloads, videos, and articles. I used the traditional template hierarchy to create a unique look for the archive page for this CPT (the page that lists all posts from the CPT) by making a file called archive-knowledge_base.php but then I found that my search results did not use this custom template but instead the default search.php
I found that there is not template hierarchy for search.php to account for custom taxonomies or post types. Instead of creating a number of conditional statements inside of search.php I simply overrode the normal hierarchy to force WordPress to use my archive-knowledge_base.php template to display my results. This keeps all results and lists consistent in their layout.
How to use it:
It’s absolutely simple! We will add something into our functions.php Check out the code below.
//Get the post type of the query object
$post_type = get_query_var('post_type');
//Check if I am doing a search query for the post type 'knowledge_base'
if( $wp_query->is_search && $post_type == 'knowledge_base' )
// replace the normal results with my custom archive page
This is a very simply snippet of code. First you are getting the $query_var which is a variable from the $wp_query object, in this case the post type. Once we have that we check if WordPress is running a search query and it is for our defined custom post type called ‘knowledge_base’. If both of those things are true, we define the new highest priority template using locate_template. Finally, we take that code and apply it to the template_include filter hook which is applied before WordPress decides which template on the Template Hierarchy rank to use.