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

WordPress21K阅读模式

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

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

通过插件创建 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'] = __( '模板名称' );

 

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  2  访客  2
    • 欧乐安
      欧乐安 3

      这个不错,随心定义

      • 鸿硕
        鸿硕 0

        页面属性中模板可以选择,但是打开页面加载的模板不是自定义的。

      匿名

      发表评论

      匿名网友
      :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

      拖动滑块以完成验证