Here, is the new article about WordPress. This article is about to explain how to use parent category template for child category in WordPress.
So, In this short tutorial, we will see the function which will make a subcategory follow the template of its parent means to use parent category template while viewing for all child categories. Because it is quite complicated to create a separate template file every time you create a new Subcategory or category and it’s not good to create the template file for each and every category.
Read: Cookie Free domain in WordPress and WordPress Multisite Explained
You need to copy and paste following line of code into your theme’s function.php
file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function parent_category_template() { if ( !is_category() || is_404() ) return; // if no category or not found $cat = get_query_var('cat'); $category = get_category ($cat); if($category->category_parent!='' || $category->category_parent !=0){ $parent_category = get_category ($category->category_parent); if($parent_category->category_parent !=0){ $parent_category = get_category ($parent_category->category_parent); } } if ( !($category) ) return; // no category found if ( file_exists(TEMPLATEPATH . '/category-' . $category->cat_ID . '.php') ) { exit; } elseif ( file_exists(TEMPLATEPATH . '/category-' . $parent_category->slug . '.php') ) { include(TEMPLATEPATH . '/category-' . $parent_category->slug . '.php'); exit; } } add_action('template_redirect', 'parent_category_template'); |
Above function will check if category’s own template not exists, will check for parent category template and will display parent category’s template.
I hope that you liked this simple technique and helps someone.
Don’t hesitate to use this code in your WordPress projects and post your comments if you need help. As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.