以插件形式在WordPress中引入页面模板(自定义页面)

在 WordPress 中可以使用不同的页面模板创建页面,一般情况下,页面模板由主题引入,以page-xxx.php
的形式存于主题文件夹内。如果想将其他位置的文件注册成页面模板,该如何做呢?
需求
最近写一个插件,目的是将已有的页面模板注册至 WordPress 页面模板列表中。传统方式引入页面模板需要将文件拷贝至主题目录中,但这样就违背了插件的初衷。
我希望插件可以将插件文件夹或其他位置的模板文件注册至 WordPress 页面模板列表中,这样,使用者无论是安装还是更新模板,只需要安装或更新插件就可以了。
这样做还有一个好处,即便使用者更换了主题,我插入的页面模板依旧正常工作。
实现
WordPress 提供了两个模板加载相关的 Hook。
- theme_page_templates
theme_page_templates
是 WordPress 获取页面模板列表时调用的函数钩子。//野/兔@梓/喵/出/没(www.azimiao.com) apply_filters( 'theme_page_templates', array $page_templates, WP_Theme $this, WP_Post|null $post )
其中,
$page_templates
即为原始的页面模板列表数组。 -
template_include
template_include
是 WordPress 在 include 模板文件前获取模板文件路径时调用的函数钩子。//梓@喵@出@没/博/客azimiao.com apply_filters( 'template_include', string $template )
其中,
$template
即为原始的页面模板文件路径。
利用上面的两个函数钩子,即可轻松完成需求,示例代码如下:
//定义模板文件路径前缀,这里使用插件根目录
define('ZM_PLUGIN_DIR', plugin_dir_path(__FILE__));
//要引入的外部模(梓喵出没博客|azimiao.com)板列表
$templates_new = array(
"page-mycustom.php"=>"梓喵出没1"
);
function zm_register_page(){
add_filter('theme_page_templates', 'zm_add_template');
add_filter('template_include', 'zm_view_template');
}
function zm_add_template( $posts_templates ) {
global $templates_new;
$posts_templates = array_merge( $posts_templates,$templates_new );
return $posts_templates;
}
function zm_view_template( $template ) {
global $post;
global $templates_new;
if ( !isset( $post ) ) return $template;
//拿到页面(梓喵出没博客|azimiao.com)模板名称
$t_template_name = get_post_meta( $post->ID, '_wp_page_template', true );
//页面模板不在自定义列表中,直接返回
if ( ! isset( $templates_new[ $t_template_name ] ) ) {
return $template;
}
//拼接模板(梓喵出没博客|azimiao.com)正确路径
//假设模板存放于 本插件目录/custompage/ 下
$file = ZM_PLUGIN_DIR . 'custompage/' . $t_template_name;
//(梓喵出没博客|azimiao.com)
if( file_exists( $file ) ) {
return $file;
}
return $template;
}
在上面的代码中,我利用函数钩子,将页面模板梓喵出没1
加入至 WordPress 页面模板列表中。之后,在 WordPress 载入页面模板文件时,将正确的模板文件路径返回出去。
最后,只需要在插件初始化时调用zm_register_page
,即可挂载函数钩子,代码如下:
add_action( "plugins_loaded", "zm_register_page");
验证
在 WordPress 页面编辑器中,可以(梓喵出没博客|azimiao.com)见到自定义页面梓喵出没1
已加入页面模板列表。
把它当作正常页面模板使用即可。