How To Create Custom Template for Child Categories in WordPress

How To Create Custom Template for Child Categories in WordPress
612 Views
0
(0)

The concept of themes is one of the most essential selling points of WordPress. A single theme significantly improves the aesthetics and operation of the website. However, some websites use distinct styles on different pages.

If you’ve been using WordPress for a while, you’re probably familiar with its basic structure and the primary features it offers to bloggers. WordPress comes with two kinds of content by default: posts and pages.

Posts are further subdivided into categories and tags, and you can convert categories to tags and tags to categories as needed. You can create a separate page for each specific type of content, such as a blog, a shop, a contacts page, and so on.

<?php
add_filter( 'category_template', 'cxc_custom_category_templates' );

function cxc_custom_category_templates( $template ) {
	$category = get_category( get_queried_object_id() );
	if ( $category->category_parent > 0 ) {
		$sub_category_template = locate_template( 'child-category.php' ); // specify template name which you create for child category
		$template = !empty($sub_category_template) ? $sub_category_template : $template;
	}
	return $template;
}
?>
  • The code is a function that is called when the category template is being set.
  •  The code first checks to see if the current category has any parent categories.
  •  If it does, then it looks for a child-category.php template and sets the custom template as its value otherwise, it uses the default category template which is specified in wc_custom_category_templates().
  •  The code starts by getting the ID of the current object from get_queried_object() and calling get_category() on this object to retrieve its parent categories.
  •  Then, if there are any parents, then locate a child-category.php file and use that as an alternative custom template for this particular category’s page layout instead of using wc_custom_category_templates().
  •  The code will add a filter to the category template which is used for all categories.
  •  The code above will locate the child-category.php template and use that as the default template if one does not exist in this case.

How useful was this blog?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this blog.

Leave a comment

Your email address will not be published. Required fields are marked *