A situation may arise that you have to load different templates based on different post categories. Working on a project I had to load different template based on different categories. So, thought about sharing the code with the community.

You have to write a filter function in your “function.php” file and a condition in your “single.php” file.

add the following code inside functions.php
 function get_custom_category_template($single_template)
{
    global $post;
    if (in_category('your_category1')) {
        $single_template = dirname(__FILE__) . '/view/category-one-view.php';
    }

    if (in_category('your_category2')) {
        $single_template = dirname(__FILE__) . '/view/category-two-view.php';
    }


    return $single_template;
}
add_filter("single_template", "get_custom_category_template");
   

Code Explanation

  1. I have kept the template files in ‘view’ subdirectory inside ‘mytheme’ folder. Hence ‘/view/template….’. The template files should have get_header(), get_footer() functions called to have all the styles and scripts loaded in the custom template layouts.
  2. Carefully read the codes in ‘single.php’ file. The template names are called with not .php extension and category in the second parameter.
Finishing Touchup

This is an excellent approach for those who are obsessed with custom templating and styling in different areas of their websites. Hope it helps. Share your thoughts on comments below. Happy Coding…

Categories: WordPress

Zafor Iqbal

Full Stack Web Developer, Entrepreneur

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.

0
    0
    Your Cart
    Your cart is emptyReturn to Shop