How to add single category posts template to your wordpress theme

Recently, I was implementing a private site in wordpress. So, I wanted to give privilege to some users only to be able to read posts under a certain category say  ‘news’ . But according to wordpress template hierarchy only categories can have separate templates by using category-{slug}.php

But there is a way out for single-{category-slug}.php

Just add the following code to your functions.php

add_filter('single_template', create_function(
    'foreach( (array) get_the_category() as $cat ) {
        if ( file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php") )
            return TEMPLATEPATH . "/single-{$cat->slug}.php"; 
    return $the_template;'  )

That’s it. After this, in my case I simply added a template file single-news.php  to my theme folder.

Leave a Reply

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