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

WPOCN WordPress教程评论40阅读模式

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

将下面的代码添加到插件中:

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

其中:

模板文件:template.php

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

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

文章末尾固定信息

weinxin
我的微信
我的微信
微信扫一扫
 
WPOCN
  • 本文由 WPOCN 发表于 2022年11月24日14:50:59
  • 转载请务必保留本文链接:https://www.tghello.com/4340.html

发表评论