我想在插件中添加新的自定义模板(定制-page.php,定制-single.php)。当激活时,我想动态地使用插件的自定义模板来覆盖主题的模板(page.php,single.php)。
有什么函数可以做到这一点吗?
发布于 2018-03-06 05:41:13
可以这样做的一种方法是向钩子{$type}_template添加一个过滤器。
样本代码:
function my_plugin_custom_template( $template, $type ) {
switch ( $type ) {
case 'page':
$template = '/path/to/custom-page-template';
break;
case 'single':
$template = '/path/to/custom-single-template';
break;
}
return $template;
}
add_filter( 'page_template', 'my_plugin_custom_template', 10, 2 ); // Filter for page.php
add_filter( 'single_template', 'my_plugin_custom_template', 10, 2 ); // Filter for single.php或者,也可以向钩子template_include添加一个筛选器。
样本代码:
function my_plugin_custom_template2( $template ) {
if ( is_page() ) {
$template = '/path/to/custom-page-template';
}
elseif ( is_single() ) {
$template = '/path/to/custom-single-template';
}
return $template;
}
add_filter( 'template_include', 'my_plugin_custom_template2' );应该由您来决定筛选哪个钩子;但是,template_include过滤器是在{$type}_template钩子之后调用的。如果查看my_plugin_custom_template()代码,基本上不需要检查当前页面(即查询对象)是否是Page、Post等。
希望这能帮上忙。
https://wordpress.stackexchange.com/questions/295896
复制相似问题