a blog by Christian Snodgrass
about programming, web and game design, and everything else

Changing WordPress Template with template_include

I’m working on this handy little plugin so I can create code demos, so I can demo HTML, CSS, and Javascript pages for my articles, without having to create a page and FTP it up. I want to just be able to create and edit it directly from the WordPress back-end.

Lucky for me, it was surprisingly easy. The biggest (and really only) tricky part was figuring out how to change which template page was loaded. I needed this because I wanted to have a template file in my plugin folder which was a super stripped down file that wouldn’t influence my demo.

After a little reverse engineering, I found what I was looking for: the template_include filter.

template_include Filer

The template_include filter is found near the bottom of the wp-includes/template-loader.php file.

It’s pretty simple: it passes you the template file (with a full file path) it thinks you should use, and your filter should return the full file path of the template you want to use.

In my case, I created a custom post type for the plugin, so all I did was check if the post in question was the same type as my code demo. If it was, I return the special code demo template in my plugin folder. If it wasn’t, I’d just return the same path it gave me.

Here is the excerpt:

// The first 1 is priority 1. In this case, it doesn't really matter. 
// The second 1 means our callback takes 1 parameter. 
add_filter('template_include', 'my_template', 1, 1); 
 
// @param $template - Full path to the normal template file. 
function my_template($template) { 
  global $post; 
 
  if($post->post_type == 'my_post_type') 
    return dirname(__FILE__) . '/my_special_template.php'; 
  return $template; 

And that’s it… pretty simple. As with any filter, it’s important to remember to always return a value. If you don’t, weird things will happen (in this case, it wouldn’t load anything for the template, resulting in an empty page).

Hopefully this will help someone out as I couldn’t find anything googling things and ended up reverse-engineering on my own.

Xazure Code Demo

Just a heads up, the plugin I mentioned will be available to download from here in the next few days (and hopefully from the WordPress repository once I figure out the hoops I need to jump through). More on that later. ;)


Related Articles


Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Back to Top