Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make *ALL* Wordpress Categories use their Parent Category Template

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.

like image 202
Matrym Avatar asked Jun 25 '10 17:06

Matrym


People also ask

How do I assign a category to a template in WordPress?

Connect to your WordPress hosting using an FTP client and then go to /wp-content/themes/your-current-theme/ and upload your category-design. php file to your theme directory. Now, any changes you make to this template will only appear in this particular category's archive page.

How do I find parent and child category in WordPress?

Use following code for to get children category of parent category. <? php $parent_cat_arg = array('hide_empty' => false, 'parent' => 0 ); $parent_cat = get_terms('category',$parent_cat_arg);//category name foreach ($parent_cat as $catVal) { echo '<h2>'.


1 Answers

/**
 * Iterate up current category hierarchy until a template is found.
 * 
 * @link http://stackoverflow.com/a/3120150/247223
 */ 
function so_3119961_load_cat_parent_template( $template ) {
    if ( basename( $template ) === 'category.php' ) { // No custom template for this specific term, let's find it's parent
        $term = get_queried_object();

        while ( $term->parent ) {
            $term = get_category( $term->parent );

            if ( ! $term || is_wp_error( $term ) )
                break; // No valid parent

            if ( $_template = locate_template( "category-{$term->slug}.php" ) ) {
                // Found ya! Let's override $template and get outta here
                $template = $_template;
                break;
            }
        }
    }

    return $template;
}

add_filter( 'category_template', 'so_3119961_load_cat_parent_template' );

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

like image 178
TheDeadMedic Avatar answered Sep 20 '22 14:09

TheDeadMedic