Themergency

Template File Loader Class

Pippin recently posted a tutorial about a template file loader class, which I thought would be a great addition to any complex plugin that uses templates for shortcode output.

What Is A Template Loader?

In a nutshell, a template loader scans a number of different locations for a template file (just a plain old php file). If it finds the desired template, it is included. If no other template is found, then a default is included. This makes it really easy for theme authors to override any templates that you have in your plugin. And by placing them in a specific folder inside their theme, it means that your plugin updates will never override the theme templates. Oh yes, and it also supports parent and child themes.

How To Use The Template Loader Class

It is a class, so you have to extend Gamajo_Template_Loader with your own class. Here is a really simple example:

class FooBar_Template_Loader extends Gamajo_Template_Loader {
	/**
	 * Prefix for filter hooks called within the class.
	 */
	protected $filter_prefix = 'foobar';
	/**
	 * Directory name where custom templates for this plugin should be found in the theme.
	 */
	protected $theme_template_directory = 'foobar-templates';
	/**
	 * Reference to the root directory path of your plugin.
	 */
	protected $plugin_directory = FOOBAR_PLUGIN_DIR;
}

Now you can instantiate this class and call get_template_part:

$loader = new FooBar_Template_Loader();
$loader->get_template_part('email', 'body');

As soon as it finds the specific file in one of the above locations, it stops looking any further and includes the file. Also notice how it first looks for the more specific file email-body.php and then the less specific email.php. It also checks the parent theme folder, but only if the current theme is a child theme.

Example Plugin

Check out Pippin’s example plugin that uses the template loader class.

This is a great bit of code that can really take your plugin to a new level, especially when you are generating HTML code on the frontend.