Skip to content

Instantly share code, notes, and snippets.

@webaware
Created February 17, 2018 02:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webaware/c6d95e0336d72c3a2d1b236aa0d7763c to your computer and use it in GitHub Desktop.
Save webaware/c6d95e0336d72c3a2d1b236aa0d7763c to your computer and use it in GitHub Desktop.
I have these functions in the plugin class that accesses templates, or break them out into simple functions if I'm using a namespace
<?php
/**
* load template from theme or plugin
* @param string $template name of template to load
* @param array $templateData data to make available to templates
*/
public function loadTemplate($template, $templateData = []) {
extract($templateData);
$templatePath = $this->locateTemplate($template);
if (!is_readable($templatePath)) {
echo esc_html(sprintf(__('template not found or unreadable: %s', 'example-plugin'), $template));
return;
}
require $templatePath;
}
/**
* locate template in either theme or plugin
* @param string $template name of template to load
* @return string
*/
protected function locateTemplate($template) {
// accommodate both template names already ending with .php and names that don't
if (substr($template, -4, 4) !== '.php') {
$template .= '.php';
}
$templatePath = locate_template("plugins/example-plugin/$template");
if (!$templatePath) {
$templatePath = EXAMPLE_PLUGIN_ROOT . "templates/$template";
}
return $templatePath;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment