Setting the template for individual posts

I hashed together a plugin that enables authors to specify a specific template file to be used for a post (this functionality is already built in for pages, but not for posts).

<?php
/*
Plugin Name: Template for posts
Plugin URI: http://labs.dagensskiva.com
Description: Set the template file for a post by setting the Custom Field 'dsc_template' to the filename of the template
Version: 0.1
Author: Henrik
*/
?>

function dsc_post_template() {
  global $post, $wp_query;

  if (count($wp_query->posts) == 1) {
    $id = $wp_query->posts[0]->ID;
    if ($temp = get_post_meta($id, 'dsc_template', true)) {
      include( TEMPLATEPATH . '/' .$temp );
      exit(0);
    }
  }
}
add_filter('template_redirect', 'dsc_post_template', 9);

Usage: a Custom Field called ‘dsc_template’ is set to equal the basename of the file, e.g. ‘interview.php’, placed inside your theme folder. Simple as that. It only applies the template file if $wp_query contains only one post, i.e. where the template file ’single.php’ would normally be applied.

Tags: , ,

2 Comments to “Setting the template for individual posts”

  1. Patrik Hamberg Says:

    Fick du min buggrapport om att specifik css körde över dagens-märkningen? Är det fixat nu? Eller hade jag missat nåt i css:en? Ex. Kiss-css:en dåra.

  2. Henrik Melin Says:

    Ja, jag fick den. Jag tror att Kal ska kolla pa det dar. Hall ett oga uppe for att se om det hadner igen.

Leave a Reply