How to create a custom single.php Template in WordPress
Have you ever needed or wanted to create a custom single.php template that would only be used by posts of a certain type? When I was building the FARMcurious site I needed a way to display blog posts and product posts in different ways. The products single template needed to show price, product info, photos, and be laid out differently than blog post single template.
After looking around the WordPress community for a bit I found numerous plugins that seemed like they would do the trick, but I really hate throwing plugins at a problem unless there’s a very compelling reason to do so. After awhile though, I found a post on elliotjaystocks.com that immediately made sense, and the solution is dead simple.
Simply put: you just need your single.php file to make a few decisions for you. A simple if statement will help determine which category the post is in, and once you know that you can build the single.php template by including other (custom) templates.
The first thing you want to do is copy the code in your single.php file and save it as two new files that we’ll call using single.php. I named mine “default-single.php” and “product-single.php”.
Now, in our original single.php file, delete all of the code and replace it with something like below:
<?php
/*
Template: single.php
*/
get_header();
?>
<?php
if ( in_category( array( '6', '11' ) )) {
include(TEMPLATEPATH.'/default-single.php');
}
else {
include(TEMPLATEPATH.'/product-single.php');
}
?>
The first php block simply names the template and of course the get_header(); function grabs the header.php file.
The next php block starts an if statement, and in this example we’re looking for posts that are in a certain array of category IDs: 6 and 11. If there are any posts in those categories, we’re going include the code from the default-single.php file. Otherwise, the else statement will include the code from the product-single.php file.
In this manner you can customize your two new single.php templates any way you like, and utilize them by simply categorizing your posts appropriately.
I hope this comes in handy! Enjoy!