通过插件创建 WordPress 自定义页面模板

评论3,449

为页面选择不同页面模板是 WordPress 的一项基本功能。如果您是插件开发人员,准备为插件使用专用的模板,在不修改主题的情况下,很难为网站添加新的页面模板。可以通过下载的代码,利用插件为网站添加新的页面模板,而无需修改主题。

add_filter( 'page_template', 'zm_page_template' );
// 加载页面模板
function zm_page_template( $page_template ) {
	if ( get_page_template_slug() == 'zm-template.php' ) {
		$page_template = dirname( __FILE__ ) . '/templates/zm-template.php';
	}
	return $page_template;
}
 
// 添加到页面属性模板中
add_filter( 'theme_page_templates', 'zm_add_template_select', 10, 4 );
function zm_add_template_select( $post_templates, $wp_theme, $post, $post_type ) {
	$post_templates['zm-template'] = __( '模板名称' );
	return $post_templates;
}

其中:

模板文件:zm-template.php

模板文件路径:/templates/zm-template.php

显示在页面属性中的模板名称:$post_templates['zm-template'] = __( '模板名称' );

 

发表评论