Category and subcategory control which single post template should load?

Community Forums Forums General Discussion Category and subcategory control which single post template should load?

This topic is: not resolved

This topic contains 2 replies, has 2 voices, and was last updated by  kriskl 7 months, 3 weeks ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #63863

    kriskl
    Participant
    Post count: 37

    Hi,
    here is the scenario
    I have 2 (or more) categories and each has 5 (or more) subcategories

    cat1 – veg (subcat: 1) carrot 2) tomato etc
    cat2 – fruit (subcat: 1) apple 2) orange etc

    I have created for each category single templates:
    single-veg.php, single-fruit.php ..

    So, does anyone know what should be the correct function to load single-veg.php on all posts which belong to subcategories: ‘veg’, ‘carrot’ etc category??

    This is what I have adopted, but I think there must be a better way.. and of course, if you notice anything wrong with the code… I am newbie
    any help would be appreciated

    /** Get Post Category and sub category */
    
    function post_is_in_descendant_category( $cats, $_post = null )
    {
    	foreach ( (array) $cats as $cat ) {
    		// get_term_children() accepts integer ID only
    		$descendants = get_term_children( (int) $cat, 'category');
    		if ( $descendants && in_category( $descendants, $_post ) )
    			return true;
    	}
    	return false;
    }
    
    /** Conditional Templates for Single posts */
    
    function template_change( $template ){
    
        if( is_single() && (post_is_in_descendant_category('12')) || in_category('12') ){
            $templates = array("single-veg.php");
    	}
    		
       elseif( is_single() && (post_is_in_descendant_category('17')) || in_category('17') ){
            $templates = array("single-fruit.php");
    		
        } elseif( is_single() && in_category('articles') ){
            $templates = array("single-articles.php");
       
        }
        $template = locate_template( $templates );
        return $template;
    }
    
    add_filter( 'single_template', 'template_change' ); //'template_include'/'single_template'
    
    
    #74467

    Susan
    Moderator
    Post count: 7988

    Hi, as you posted this a while back, I hope you got your issue resolved. If not, please check back, and I will escalate for you. If it is resolved, please mark “resolved”, and I will close it. Thanks!


    Susan @ Graphically Designing I’d love to customize your website! I tweet!
    I’ve taken up the challenge! – help me answer some of the unanswered posts

    #76982

    kriskl
    Participant
    Post count: 37

    Thanks Susan

    Yes, it is resolved, I received help on another forum

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.