Forums

Get sub-category to use its parent category template (8 posts)

  1. leandrocorrea
    Member
    Posted 2 years ago #

    Hello,
    I'm having trouble dealing with sub-categories templates. Right now, for diferent category IDs, I use different template files, such as category-1.php, category-2.php, category-3.php, and so on. That works fine.

    But when displaying posts from a sub-category, WordPress go straight to category.php template file. All I need is a way to make WordPress choose the parent category template file when displaying its sub-categories and all future new sub-categories to be created.

    Example: Make all sub-categories of category ID 3 to use the category-3.php template, and NOT category.php template.

    Can anyone help me? :)

  2. MichaelH
    Volunteer
    Posted 2 years ago #

  3. MK009
    Member
    Posted 2 years ago #

    Michael, it seems the plugin makes values from custom fields disappear. I understand the original plugin had this issue too, as two people mentioned here:

    http://wordpress.org/support/topic/230590?replies=12

    It would be great if this could be resolved. This must be a very common requirement. The only other option is heaps of subcategory php files, all exactly the same other than their file name. :/

  4. MK009
    Member
    Posted 2 years ago #

    I put your code into a filter in functions.php instead and it then works with custom fields:

    add_filter('category_template','my_category_template_filter');
    function my_category_template_filter(){
    
    	$cat = get_query_var('cat');
        $category = get_category ($cat);
    
    	if ( file_exists(TEMPLATEPATH . '/category-' . $category->cat_ID . '.php') ) {
    		$file = TEMPLATEPATH . '/category-' . $category->cat_ID . '.php';
    	} elseif ( file_exists(TEMPLATEPATH . '/category-' . $category->category_parent . '.php') ) {
    		$file = TEMPLATEPATH . '/category-' . $category->category_parent . '.php';
    	}
    
        return $file;
    }

    Disclaimer: I have no idea if this is a good idea or not, as I have almost zero idea how actions / filters work. I did see someone filtering the category template for other reasons (to run names instead of ID's in the file names) so assumed this would work too.

  5. MichaelH
    Volunteer
    Posted 2 years ago #

  6. MK009
    Member
    Posted 2 years ago #

    That one also has the custom fields disappearing problem according to the last poster here:

    http://wordpress.org/support/topic/230590?replies=12

  7. MichaelH
    Volunteer
    Posted 2 years ago #

    I installed and tested with custom fields in a category template at version 2.8. Don't know what more to say.

  8. leandrocorrea
    Member
    Posted 2 years ago #

    Thanks all for your help, I'll make some tests and return with feedback.

Topic Closed

This topic has been closed to new replies.

About this Topic