要在页面属性模板部分添加自定义模板,您必须首先将模板添加到下拉列表中并加载到template_include
当当前页面选择它作为当前模板时挂钩。
/**
* Add "Custom" template to page attirbute template section.
*/
function wpse_288589_add_template_to_select( $post_templates, $wp_theme, $post, $post_type ) {
// Add custom template named template-custom.php to select dropdown
$post_templates[\'template-custom.php\'] = __(\'Custom\');
return $post_templates;
}
add_filter( \'theme_page_templates\', \'wpse_288589_add_template_to_select\', 10, 4 );
/**
* Check if current page has our custom template. Try to load
* template from theme directory and if not exist load it
* from root plugin directory.
*/
function wpse_288589_load_plugin_template( $template ) {
if( get_page_template_slug() === \'template-custom.php\' ) {
if ( $theme_file = locate_template( array( \'template-custom.php\' ) ) ) {
$template = $theme_file;
} else {
$template = plugin_dir_path( __FILE__ ) . \'template-custom.php\';
}
}
if($template == \'\') {
throw new \\Exception(\'No template found\');
}
return $template;
}
add_filter( \'template_include\', \'wpse_288589_load_plugin_template\' );
theme_page_templates
挂钩可用于
page
岗位类型。如果要将自定义模板添加到其他帖子类型,则必须替换
page
使用自定义帖子类型名称,例如。
event
post类型挂钩将有一个名称
theme_event_templates
.