Make Money Online
Make Money Online

Reputation: 1

How to apply parent category template for child category in wordpress?

I tried to build custom template for specify category, my category is news and I create a template with name "category-news.php" , in "news" category I have some child category, now I want to apply the parent category template for child category, I test this code bellow but it doesn't work.

function wp_category_template() {
$category = get_queried_object();
$parent_id = $category->category_parent;
$templates = array();
if ( $parent_id == 0 ) {
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
$templates[] = 'category.php';
} else {
$parent = get_category( $parent_id );
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
$templates[] = "category-{$parent->slug}.php";
$templates[] = "category-{$parent->term_id}.php";
$templates[] = 'category.php';
}
return locate_template( $templates );
}
add_filter( 'category_template', 'wp_category_template' );

Upvotes: 0

Views: 641

Answers (1)

Martin
Martin

Reputation: 98

Maybe you can try the following:

Create new file called template-news.php and move the content from category-news.php to that file.

Then is category.php you can check if category is news or if the category has parent category of news then load the template-news.php file.

In category.php add this:

$category = get_queried_object();
$parent = false;
if ( $category->parent ) {
    $parent = get_term_by('id', $category->parent, 'category');
}
if ( is_category('news') || ( $parent && $parent->slug === 'news' ) {
    include_once get_template_directory() . '/template-news.php';
}

Note: I haven't tested this, but the concept is clear.

Upvotes: 1

Related Questions