Wordpress

By default all Wordpress posts viewed as a single post are controlled by the particular theme’s “single.php” file.

Wordpress, by default is setup to use one template file (“single.php“) for every post.(But what if you wanted to display a different layout or different code dependent on the specific categories a post or filed into?

To do this with Wordpress; one needs to use a bit of PHP in the “single.php” file and create category specific files.

In the below example lets assume the following:

  • Category 2 is my Blog
  • Category 15 is a Photography section
  • Category 18 is a Video section

I want to display a different layout according to the particular post’s category so I would edit “single.php” as follows:

<?php $post = $wp_query->post; if ( in_category('2') ) { include(TEMPLATEPATH . '/single-blog.php'); } elseif ( in_category('15') ) { include(TEMPLATEPATH . '/single-photography.php'); } elseif ( in_category('18') ) { include(TEMPLATEPATH . '/single-video.php'); } else { include(TEMPLATEPATH . '/single-default.php'); } ?>

Proceeding editing this, the referenced files must be created e.g. “single-blog.php“, “single-photography.php” and “single-video.php” file referenced above. Also a “single-default.php” file should also be created so that any post that is not in any of the specified categories (15, 18 ir 2) will just use a default template file – “single-default.php“.

  • shihab malayil

    how i can find the category if iam using Custom Post type ..?

  • Demo

    thaks , this is what i want to do.its very helpful for me.thanks a lot

  • Pboudeville

    Greeeaaaaat !!! I'm going to try right now, that's exactly what i'm looking for :). Thank you for this post !

  • Thank  you for this post. Works perfectly :)

  • I was looking for this only.. Its nice put up.. Excellent trick.. Now I can Implement Different Templates for Different Posts Category in my site 
    http://www.c4learn.com/ thank you very much again..

blog comments powered by Disqus