Sunday 17 November 2013

Using A Different Post Template For Posts Within A Specific Category

Important: All scripts hosted on widcraft.googlecode.com don't work anymore because Google has blocked that SVN repository.
On Thursday I posted an article about using different post template for posts formats, but now it's time for doing the same thing with categories, instead of formats. You can use this trick in your WordPress to create different type of posts, such as portfolio items.

We discussed everything previously, so let's get into this trick:

Using A Different Post Template:

In this tutorial, we'll create a different post template for the cat-1 category. We'll use multiple single.php files to make it more easy and customizable.

Create a single.php file for your category. We're going to name it single-cat-1.php. You can also copy your single.php file to this template and make some changes that you want in the video template.

Upload single-cat-1.php to the root of your current theme. Same place where single.php file is located.

Okay, so now we'll tell WordPress to use single-cat-1.php template for the posts within video category. Add following to your 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;

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

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

In above code, replace cat-1 is the slug of your category, and single-cat-1.php is your custom post template file. Save the file. That's it.
Important: Check our new website TricksPanda.com for WordPress tutorials, plugins and more.
 
Powered by Blogger.