0

I've a custom post type that I manage with a custom taxonomy. I've made a template: taxonomy-brand.php, to show the top level categories of the taxonomy. Now I'd need to show the subcategories of each of these, in another different template. I guess that it's possible to use the template_include filter, but I can't implement precisely and which condition to evaluate

0

You could use the template_include hook to load a specific template for your taxonomy. You would need to change out any instances of my-taxonomy with your specific custom taxonomy and switch out the brand-subcategories.php with whatever your template name is.

/**
 * Force Taxonomy Subcategories to new template
 *
 * @param String $template - Expected template path
 *
 * @return String $template
 */
function wpse303717_subcategory_template( $template ) {

    // We're not on a taxonomy page
    if( ! ( is_tax() && is_tax( 'my-taxonomy' ) ) ) {
        return $template;
    }

    // Grab the queried object, _should_ be a term but make sure.
    $queried_object = get_queried_object();

    // We either don't have the right object OR we're on a top level category becuase $term->parent === 0
    if( isset( $queried_object->parent ) && empty( $queried_object->parent ) ) {
        return $template;
    }

    // Our template could be located anywhere, we could store it in a subdirectory but 
    // we would need to specify a relative path from the theme root to it.
    // Example: 'templates/brand-subcategories.php'
    if( false !== ( $new_template = locate_template( 'brand-subcategories.php' ) ) ) {
        $template = $new_template;
    }

    return $template;

}
add_filter( 'template_include', 'wpse303717_subcategory_template' );

If you want to load a specific template per subcategory you would need to test against $queried_object->term_id vs what you expect. Though do note that your client could delete these terms which would throw off your code.

| improve this answer | |
  • Hy Howdy! Thank you so much, you give me a big help. I need just this kind of solution. – Fibonacci May 18 '18 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.