这是一个插件,它正在注册一个自定义帖子类型(CPT),并从插件中推送模板文件,用于特定的CPT。
<?php
/**
* Plugin Name: WPSE352898 Template Test
* Author: Mayeenul Islam
* Author URI: https://mayeenulislam.github.io
*/
/**
* Register My Custom Post Type.
*/
function wpse352898_register_cpt() {
register_post_type(\'mycpt\', array(
\'labels\' => array(
\'name\' => \'My CPT\',
\'singular_name\' => \'My CPT\',
\'menu_name\' => \'My CPT\',
),
\'public\' => true,
\'publicly_queryable\' => true,
\'exclude_from_search\' => false,
\'has_archive\' => true,
\'query_var\' => true,
\'rewrite\' => true,
));
}
add_action( \'init\', \'wpse352898_register_cpt\' );
/**
* Template loader
*
* @param string $template The template that is called.
*
* @return string Template, that is thrown per modification.
*/
function wpse352898_template_loader( $template ) {
$find = array();
$file = \'\';
if ( is_single() && \'mycpt\' === get_post_type() ) {
// Singular template for CPT \'mycpt\' in a theme.
$file = \'single-mycpt.php\';
$find[] = $file;
// Directory in a theme, where user can define their custom template to override plugin imposed template.
$find[] = \'mycpt-templates/\' . $file;
}
if ( $file ) {
$template = locate_template( array_unique( $find ) );
if ( ! $template ) {
// Load template file from the plugin under this directory.
$template = untrailingslashit( plugin_dir_path( __FILE__ ) ) . \'/templates/\' . $file;
}
}
return $template;
}
add_filter( \'template_include\', \'wpse352898_template_loader\' );
激活插件后,您需要通过将表单保存在中手动刷新重写规则
Settings » Permalinks 没有任何修改。但您也可以刷新上插件的重写规则
register_activation_hook
(此处未显示)。
要显示插件中的模板文件,插件将在此处查看模板:<plugin>/templates/single-mycpt.php
.
将提供覆盖活动主题中的插件强制模板的功能,它将在此处查看被覆盖的模板:<active-theme>/mycpt-templates/single-mycpt.php
.
希望有帮助。:)