本页目录

在开发 WordPress 主题时,在主题里添加自定义页面模板很简单,那么,怎么用插件来添加自定义页面模板呢?我在开发插件时有这个需求,通过互联网知道了一点有用的信息,这一次的 WordPress 开发教程就分享下通过插件添加自定义页面模板这个方法。
自定义页面模板:
我们在主题根目录下新建文件夹:page,在 page 文件夹中添加文件page-test.php文件,填入以下内容:
<?php/* template name: Test页面 */get_header();?>恭喜你,成功了<?php get_footer();核心:
我们在插件中添加以下代码,让插件加载模板文件并调用
//添加页面模板//从特定页加载模板add_filter( 'page_template', 'wpa3396_page_template' );function wpa3396_page_template( $page_template ){
if ( get_page_template_slug() == 'page-test.php' ) { $page_template = dirname( __FILE__ ) . '/page/page-test.php'; } return $page_template;}
/** * 将“自定义”模板添加到页面属性模板部分。 */add_filter( 'theme_page_templates', 'wpse_288589_add_template_to_select', 10, 4 );function wpse_288589_add_template_to_select( $post_templates, $wp_theme, $post, $post_type ) {
// 添加自定义模板到页面选择下拉列表 $post_templates['page-test.php'] = __('Test页面');
return $post_templates;}效果验证:
转到后台新建页面,选择 Test 页面模板即可看到效果。
如果是从主题中新建自定义页面模板,那就更简单了,大家可参考这篇 WordPress 开发教程: