views:

181

answers:

3

I want to change the default template hierarchy behavior, and force all subcategory level pages that don't have their own category template file to refer to their parent category template file. In my other post, Richard M. gave an excellent answer that solved the problem for an individual subcategory. Does anyone know how to abstract it?

function myTemplateSelect()
{
    if (is_category()) {
        if (is_category(get_cat_id('projects')) || cat_is_ancestor_of(get_cat_id('projects'), get_query_var('cat'))) {
            load_template(TEMPLATEPATH . '/category-projects.php');
            exit;
        }
    }
}

add_action('template_redirect', 'myTemplateSelect');

Thanks in advance.

+5  A: 
function load_cat_parent_template()
{
    global $wp_query;

    if (!$wp_query->is_category)
        return true; // saves a bit of nesting

    // get current category object
    $cat = $wp_query->get_queried_object();

    // trace back the parent hierarchy and locate a template
    while ($cat && !is_wp_error($cat)) {
        $template = TEMPLATEPATH . "/category-{$cat->slug}.php";

        if (file_exists($template)) {
            load_template($template);
            exit;
        }

        $cat = $cat->parent ? get_category($cat->parent) : false;
    }
}
add_action('template_redirect', 'load_cat_parent_template');

This loops up the parent hierarchy until an immediate template is found.

TheDeadMedic
I just tried this and couldn't get it to work. Would you mind double checking it?
Matrym
`TEMPLATEPATH` rather than `TEMPLATE_PATH`
Richard M
Good spot - updated :)
TheDeadMedic
@Richard - Worked!
Matrym
A: 

The TEMPLATEPATH variable might not work for child themes - looks in parent theme folder. Use STYLESHEETPATH instead. e.g.

$template = STYLESHEETPATH . "/category-{$cat->slug}.php";
Teeks
A: 

Where does this code need to go? Is it possible you could give a brief summary of how and where to implement this code?

adb