我关注了一篇文章here,它提供了如何将页面模板添加到WordPress插件的说明。它完美地工作,除了它将路径的所有部分作为类添加到body标签,即:template-users template-username template-local-sites etc
它似乎将路径分解为一个数组,并为数组中的每个项添加一个类。有人能解释为什么会这样吗?
<?php
class Plugin_Templates_Loader {
/**
* Templates folder inside the plugin
*/
private $template_dir;
/**
* Templates to be merged with WP
*/
private $templates;
/**
* Filtering and loading templates
*/
public function __construct ( ) {
$this->template_dir = plugin_dir_path(__FILE__) . '../templates/';
$this->templates = $this->load_plugin_templates();
add_filter('theme_page_templates', array($this, 'register_templates_filter'));
add_filter('template_include', array($this, 'add_template_filter' ));
}
/**
* Loading templates from the templates folder inside the plugin
*/
private function load_plugin_templates ( ) {
$template_dir = $this->template_dir;
// Reads all templates from the folder
if (is_dir($template_dir)) {
if ($dh = opendir($template_dir)) {
while (($file = readdir($dh)) !== false) {
$full_path = $template_dir . $file;
if (filetype($full_path) == 'dir') {
continue;
}
// Gets Template Name from the file
$filedata = get_file_data($full_path, array(
'Template Name' => 'Template Name',
));
$template_name = $filedata['Template Name'];
$templates[$full_path] = $template_name;
}
closedir($dh);
}
}
return $templates;
}
/**
* theme_page_templates Filter callback
*
* Merges plugins' template with theme's, making them available for the user
*
* @param array $theme_templates
* @return array $theme_templates
*/
public function register_plugin_templates ( $theme_templates ) {
// Merging the WP templates with this plugin's active templates
$theme_templates = array_merge($theme_templates, $this->templates);
return $theme_templates;
}
/**
* template_include Filter callback
*
* Include plugin's template if there's one chosen for the rendering page
*
* @param string $template path
* @return string $template path
*/
public function add_template_filter ( $template ) {
$user_selected_template = get_page_template_slug($post->ID);
// We need to check if the selected template
// is inside the plugin folder
$file_name = pathinfo($user_selected_template, PATHINFO_BASENAME);
$template_dir = $this->template_dir;
if (file_exists($template_dir . $file_name)) {
$is_plugin = true;
}
// If selected template is not empty, it's not the Default Template
// AND if it's a plugin template, we replace the normal flow to
// include the selected template
if ( $user_selected_template != '' AND $is_plugin ) {
$template = $user_selected_template;
}
return $template;
}
}
谢谢
1条答案
按热度按时间t30tvxxf1#
要解决此问题,您需要更新构造函数中的拼写错误,以使用正确的属性名称: