PHP WordPress

Modifying the WordPress Template Hierarchy to Handle Parent Categories

This is essentially plagiarism of a great post by Drew Jaynes. It took me a while to discover his post when trying to figure out how to modify the WordPress template hierarchy so I decided to share it again. Hopefully one of these pages will start to rank better.

Here’s his code with a tiny amount of additional comments:

//this code should be pasted into your function.php file
function new_subcategory_hierarchy() {  
    $category = get_queried_object();
    $parent_id = $category->category_parent;
    $templates = array();
    // preserves the classic WordPress template hierarchy for parent categories
    // or else it create a new path for sub-categories
    if ( $parent_id == 0 ) {
        // Use default values from get_category_template()
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";
        $templates[] = 'category.php';      
    } else {
        // Create replacement $templates array 
        $parent = get_category( $parent_id );
        // Current first
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";
        // Parent second
        $templates[] = "category-{$parent->slug}.php";
        $templates[] = "category-{$parent->term_id}.php";
        $templates[] = 'category.php';  
    return locate_template( $templates );
add_filter( 'category_template', 'new_subcategory_hierarchy' );

Personally, I find the WordPress Template Hierarchy pretty good. Other than it’s issue with dealing with sub-categories, I’ve never really had a problem with its flow. In fact, I could have easily just copy pasted a template file for each sub-category based on its parent.

You Might Also Like


  • Reply
    Drew Jaynes
    September 17, 2015 at 6:57 am

    +1. I think that post is probably the highest ranking on my blog ever. Goes to show that it’s a pretty common problem, I suppose.

    • Reply
      Philip Tomlinson
      September 21, 2015 at 1:58 am

      I’m sure it is!

      I’m guessing I shouldn’t be publishing articles on my dev because your comment totally surprised me.

    Leave a Reply