get_template_part for plugins - markhowellsmead/helpers GitHub Wiki
/**
* Plugin equivalent of get_template_part()
*
* @param string $file_path
* @param array ...$attrs Variable name follows the convention of core.
* @return void
*/
public function getTemplatePart(string $file_path, array $attrs)
{
if (false === strpos($file_path, '.php')) {
$file_path .= '.php';
}
$plugin = shp_must_use();
$template = "{$plugin->path}/{$file_path}";
$attrs = $attrs[0] ?? [];
if (file_exists($template)) {
include $template;
} else {
error_log("shp_must_use: Template {$template} not found.");
}
}
To then get the variables which you've passed into the file through the third parameter $vars
, use extract($args);
in the included file.
shp_must_use
Usage of This returns an instance of the plugin controller, so that we don't keep recreating it. Because the Plugin base is namespaced, place the function definition in inc/functions.php…
<?php
/**
* These functions are required in the global namespace
*/
use SayHello\MustUsePlugin\Plugin as PluginClass;
if (!function_exists('shp_must_use')) {
function shp_must_use(string $file = '')
{
return PluginClass::getInstance($file);
}
}
…and then call it in the main plugin file shp_must_use.php.
// then call
shp_must_use(__FILE__);
Plugin
class
Simplest version of the <?php
namespace SayHello\MustUsePlugin;
class Plugin
{
private static $instance;
public $path = '';
public $uri = '';
public $debug = false;
public static function getInstance(string $file = '')
{
if (!isset(self::$instance) && !(self::$instance instanceof Plugin)) {
self::$instance = new Plugin();
if (!empty($file)) {
self::$instance->path = untrailingslashit(plugin_dir_path($file));
self::$instance->uri = untrailingslashit(plugin_dir_url($file));
}
if (defined('WP_DEBUG') && WP_DEBUG) {
self::$instance->debug = true;
}
}
return self::$instance;
}
}