How To Use Custom Template For Posts Based On Categories In WordPress

If you’re running a website covering news based on many different categories then you might wanna use custom template for posts based on categories. If there are different post formats then you can also use custom template for post formats.

Using A Different Post Template

For example, we will create a different post template for wordpress category of our site. Create a single.php file for your category and name it single-wordpress.php. Drop that file to the root of your current WordPress theme.

Now add following snippet to your current theme’s functions.php file:

add_action('template_include', 'load_single_template');
  function load_single_template($template) {
    $new_template = '';

    // single post template
    if( is_single() ) {
      global $post;

      // 'wordpress' is category slugs
      if( has_term('wordpress', 'category', $post) ) {
        // use template file single-wordpress.php
        $new_template = locate_template(array('single-wordpress.php' ));

    return ('' != $new_template) ? $new_template : $template;

Above code will take the posts assigned with wordpress category and it will use single-wordpress.php file for it. That’s it. You can do same with other categories too.

If you found this post useful, share it with your friends: