The cheap-n-easy way to use “templates” in WordPress plugins

I’m continuing to work on the plugin I talked about in my last post, and have gotten to the point where we’re working on the front end display of the data. I recently sat down and really dedicated myself to figuring out the WordPress Plugin Boilerplate and really like the concept of using “partials” to reuse code for templates.

Pippin has a great article about using (full) template loaders in plugins since the builtin WordPress template_loader function is a theme function, but I didn’t need to go THAT far in this case.

My amazing coworker Martin wrote the main templating functions for the plugin that allow themes to override the plugin templates (extensibility is good!):

add_filter( 'template_include', array( self::$instance, 'ppi_load_single_template' ), 99 );
function ppi_load_single_template( $template ) {
if ( is_singular( 'things' ) ) {
// look in child or parent themes for template files first
if ( $theme_template = locate_template( 'single-items.php' ) ) {
$template = $theme_template;
} else {
$template = self::$directories['templates'] . 'single-items.php';
}
}
return $template;

I spent the better part of the morning Googling around only to arrive at the conclusion that the simplest answer is the best answer:

require_once( WASHU_PPI_PLUGIN_DIR . 'templates/partials/ppi-loop.php' );
require( WASHU_PPI_PLUGIN_DIR . 'templates/partials/' . get_post_type() . '.php' );

view raw
<multiple>.php
hosted with ❤ by GitHub

The trickiest part of this was figuring out how and where to manipulate the WordPress (global) $post variable. After much trial and error, I discovered the easiest way was to set a global variable when calling the templates from a shortcode, and then check in the template whether or not that variable was set:

global $ppi_query;
$ppi_query = new WP_Query( $args );
global $ppi_query;
global $post;
if ( $ppi_query ==null ) { $ppi_query = $wp_query; }

view raw
<multiple>.php
hosted with ❤ by GitHub

So far so good.  Next week I think I need to lay out how and why and where we’re using shortcodes.

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.