Use template of parent category for single post sub-categories

I have single post templates in a folder in my child theme marked “single”. I need the sub categories to use the same template as their parent. I’ve read a dozen tutorials all of which were more than 3 years old and don’t seem to work anymore. So what’s the correct way to do this? Here’s what I was trying.

function pa_category_top_parent_id ($catid) {
 while ($catid) {
  $cat = get_category($catid); // get the object for the catid
  $catid = $cat->category_parent; // assign parent ID (if exists) to $catid
  // the while loop will continue whilst there is a $catid
  // when there is no longer a parent $catid will be NULL so we can assign our $catParent
  $catParent = $cat->cat_ID;
}
return $catParent;
}
define(SINGLE_PATH, STYLESHEETPATH . '/single');
/**
* Filter the single_template with our custom function
*/
add_filter('single_template', 'my_single_template');
/**
* Single template function which will choose our template
*/
function my_single_template($single) {
 global $wp_query, $post;
 foreach((array)get_the_category() as $cat) :
    $categoriapadre= pa_category_top_parent_id ($cat);
    if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';
    elseif(file_exists(SINGLE_PATH . '/single-cat-' . $categoriapadre . '.php'))
    return SINGLE_PATH . '/single-cat-' . $categoriapadre . '.php';

  endforeach;
 return $single;
}

Related posts

Leave a Reply

1 comment