Theming Custom Post Types in WordPress 3.0

Please note this post is way way out of date. WordPress has since integrated CPTs fully into the template engine so that you can simple create a single-posttype.php file. [See Template Heirarchy

So today I developed a simple strategy for dealing with some of the theming issues that arise out of WordPress 3.0 and the new Custom Post Type functionality.

The Issue: You’re working on a site designed long before Custom Post Types were an itch in Matt’s¬†cerebellum. But now that the functionality is there and you want to incorporate it into your theme. Previously you used conditional code to theme your single.php file.

<?php if(in_category('foo')) { ?>
   Do something.
<?php } elseif(in_category('bar')) { ?>
   Do something else.
<?php } else { ?>
   Do yet another thing.
<?php } ?>

The thought of adding yet another layer of conditionals makes you sick to your stomach. Custom Post Types need to be treated completely different. They have different categories, taxonomies, and even different sidbars. Arg!

Solution: One simple function. Call it whatever you want, but here’s what it looks like. When I say simple … I mean simple.

function get_post_in_context() {
global $post;
$type = $post->post_type;
include(TEMPLATEPATH .'/layouts/single-'.$type .'-content.php');
}

Now just create a directory in your theme called “layouts”. Then copy and paste all the markup in your single.php file between the get_header() tag and the get_sidebar() tag to a file named single-post-content.php and save the file to your layouts folder.

Now place a the get_post_in_context() tag into your single.php  where you want the markup from single-post-content.php to show up.

<?php get_header(); ?>
<?php get_post_in_context(); ?>
 <?php get_sidebar(); ?>
<?php get_footer(); ?>

The beauty of this is that you can now create a new single-POSTTYPE-content.php (example:single-events-content.php) file for any of your custom post types and it will automagically get called instead of the single-post-content.php without any more changes to the single.php file.

I can’t take total credit for the idea. Some theme frameworks already employ a version of this strategy. But I need to adapt an existing theme rather than start from a framework. This function above will allow you to scale your existing theme to accomodate new post types without having to redesign your whole site.

About Mike Van Winkle

Ugh. I hate writing profiles. Just read the blog dude.