29 Jun

WordPress Custom Single Page Template

Posted by Mike Categories: Blog
Wordpress Custom Single Page Template

I needed to display my portfolio items in a different template than my blog posts. The problem is I post my portfolio items by adding another post and categorizing it as a portfolio item. WordPress generally treats all single posts the same, it refers to single.php and follows the template listed there. So I needed to “trick” WordPress into showing a different template if I’m viewing a portfolio item. This can be done with the following, very elegant, line of code:

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

Simply cut and paste this to your functions.php file and it will automatically search for a file named “single-{your_category_name_here}.php”. Let’s assume I have a category named “elephants,” and I need to display a custom single page template for elephants. I cut and paste the above code into my “functions.php” file. Then I create another file in my theme folder named “single-elephants.php” and include the code for my new template. WordPress will now automatically include my new template when someone tries to view a post categorized as “elephants.”

Find out more here.

One Comment on “ WordPress Custom Single Page Template ”

  1. babies December 6, 2012 at 10:06 PM

    Does your blog have a contact page? I’m having trouble locating it but, I’d like to shoot you an e-mail.

    I’ve got some recommendations for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it improve over time.

    Here is my blog post babies

Leave a Reply
  1. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>