Geek: WordPress: Quick Snippet for dynamically using custom single post templates

February 2, 2010

There exists a perfectly fine WordPress plugin called Single Post Template that allows you to assign a template to an individual post much as you can do with page templates.

Disclaimer: This post is intended for my small chunk of technical readers and posterity/helping the blog community. All regular readers who prefer things that are interesting can safely ignore this post.

As an aside, I’m kind of surprised that WordPress (at time of writing version 2.9.1) does not support this on the template-naming level in the way that it supports page-foo.php and category-foo.php naming for overriding page and category templates respectively (More about WordPress’ template hierarchy).

The Single Post Template plugin allows you to assign a post template on a post-by-post basis, but in my recent obsession with automating processes for posting, I don’t want yet another step in my publishing that can be forgotten. I know that I want all posts of a particular category with a particular custom field value to always use a completely different (i.e. not single.php) template.

How to Dynamically Use a Custom Single Post Template

It’s actually remarkably straightforward to do this but documentation out there is scarce on the template_redirect action hook. Briefly, if you hook into the template_redirect hook, you’ll want to create a function that checks the query information and decides if it’s the right kind to use whatever custom template you’d like. If so, you include that template; otherwise you simply return. Here’s an example from my functions.php file:

function lyza_single_photo_page()
{
    global $post;
    if( is_single()
            && in_category('images')
            && get_post_meta($post->ID, 'flickr_thumbnail', true)
    )
    {
        include(TEMPLATEPATH . '/single-image.php');
        exit;
    }
    return;
}
add_action('template_redirect', 'lyza_single_photo_page');

Note that if you do end up including a template in your function, you’ll need to exit afterwards. Yep, it gave me pause, too, at first.

For other conditional functions along the lines of is_single(), check out wp-includes/query.php. Also see wp-includes/template_loader.php for the way that the template_redirect hook gets called and the other logic near it, if you’re so inclined.

Of course this would work for other custom templating needs, not just single post pages.

I used this approach to show my individual photo posts in a different template:

See this in action on my site

One Comment

  1. Todd says:

    I’m going to be that guy who points out that your HTML entities have been double-escaped, as it were.

Related Posts

Scipio the Computer has deemed that these might be similar in content!
Wonderful games with Caslon