问题描述
是否可以使用插件提供自定义页面模板?
最佳解决方案
get_page_template()
可以通过 page_template
滤波器覆盖。如果您的插件是一个目录,其中包含模板作为文件,那只是传递这些文件的名称的问题。如果要 「快速创建」(在管理区域中编辑它们并将其保存在数据库中),您可能需要将它们写入缓存目录并引用它们,或者挂接到 template_redirect
并执行一些疯狂 eval()
的东西。
一个插件的一个简单的例子,如果某个标准是真的,”redirects” 到同一个插件目录中的一个文件:
add_filter( 'page_template', 'wpa3396_page_template' );
function wpa3396_page_template( $page_template )
{
if ( is_page( 'my-custom-page-slug' ) ) {
$page_template = dirname( __FILE__ ) . '/custom-page-template.php';
}
return $page_template;
}
次佳解决方案
覆盖 get_page_template()
只是一个快速的黑客。它不允许从管理屏幕中选择模板,并且页面插件是 hard-coded 插入插件,因此用户无法知道模板来自哪里。
首选解决方案是遵循 this tutorial,它允许您从 plug-in 在 back-end 中注册页面模板。然后它就像任何其他模板一样工作。
/*
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter('page_attributes_dropdown_pages_args',
array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter('wp_insert_post_data',
array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter('template_include',
array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'goodtobebad-template.php' => 'It's Good to Be Bad',
);
}
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。