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.

3 thoughts on “WordPress Custom Single Page Template

  1. 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

  2. Hello this is kind of of off topic but I was wondering if blogs use WYSIWYG editors
    or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding skills so I wanted to
    get advice from someone with experience. Any help would be greatly appreciated!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.