我正在尝试制作我的第一个插件,但我被卡住了。这是想法。当我的插件被激活时,它将为该帖子类型创建一种帖子类型和两种分类法(在我的情况下,帖子类型名称是“广告”)。另外,我创建了两个模板页面,一个用于显示所有广告帖子类型文章的列表,另一个用于显示相同帖子类型的单个页面。
现在我的问题是如何告诉 WordPress 在插件处于活动状态时从插件文件夹而不是主题文件夹中查找模板。?这是我可以在插件文件中做的事情,还是我必须为此创建另一个文件?
我正在尝试制作我的第一个插件,但我被卡住了。这是想法。当我的插件被激活时,它将为该帖子类型创建一种帖子类型和两种分类法(在我的情况下,帖子类型名称是“广告”)。另外,我创建了两个模板页面,一个用于显示所有广告帖子类型文章的列表,另一个用于显示相同帖子类型的单个页面。
现在我的问题是如何告诉 WordPress 在插件处于活动状态时从插件文件夹而不是主题文件夹中查找模板。?这是我可以在插件文件中做的事情,还是我必须为此创建另一个文件?
这应该做你正在寻找的:
首先,这个钩子告诉 WordPress 在你的插件中哪个是你的单个 CPT 模板
从这个答案中,您可以获得 single_template 钩子以及如何加载它。
如果您在插件的其他地方使用它,请定义一个常量来替换“plugin_dir_path( FILE )”,如下所示:
define('YOUR_PLUGIN_DIR_PATH', trailingslashit(plugin_dir_path( __FILE__ )) );
https://wordpress.stackexchange.com/questions/17385/custom-post-type-templates-from-plugin-folder
function load_single_ad_template( $template ) {
global $post;
if ( 'ads' === $post->post_type && locate_template( ['single-ads.php'] ) !== $template ) {
/*
* This is an 'ads' post
* AND a 'single ad template' is not found on
* theme or child theme directories, so load it
* from our plugin directory from inside a /templates folder.
*/
return YOUR_PLUGIN_DIR_PATH . 'templates/single-ads.php';
}
return $template;
}
add_filter( 'single_template', 'load_single_ad_template', 10, 1 );
然后对于广告存档模板,“archive_template”挂钩,如下所示:
function load_archive_ads_template( $archive_template ) {
global $post;
if ( is_post_type_archive ( 'ads' ) ) {
$archive_template = YOUR_PLUGIN_DIR_PATH . 'templates/archive-ads.php';
}
return $archive_template;
}
add_filter( 'archive_template', 'load_archive_ads_template', 10, 1 ) ;
官方文档:
https://developer.wordpress.org/reference/hooks/type_template/ https://codex.wordpress.org/Plugin_API/Filter_Reference/archive_template
这是未经测试的,但应该可以,但是,让我知道。