Created
February 17, 2018 02:21
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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