问题描述
我有两个自定义帖子类型 (例如 post_type_1 和 post_type_2),我想重定向到独立的模板 (single-post_type_1.php 和 single-post_type_2.php) 来处理它们的显示。我不想将显示模板放在主题文件夹中,因为我想要在其各自的插件文件夹中使用 self-contained 。
我如何让每个人都注册一个 template_redirect 钩子而不影响另一个?还是应该使用不同的技术?
目前,我在插件 1 中这样做:
add_action( 'template_redirect', 'template_redirect_1' );
function template_redirect_1() {
global $wp_query;
global $wp;
if ( $wp_query->query_vars['post_type'] === 'post_type_1' ) {
if ( have_posts() )
{
include( PATH_TO_PLUGIN_1 . '/views/single-post_type_1.php' );
die();
}
else
{
$wp_query->is_404 = true;
}
}
}
这在插件 2:
add_action( 'template_redirect', 'template_redirect_2' );
function template_redirect_2() {
global $wp_query;
global $wp;
if ( $wp_query->query_vars['post_type'] === 'post_type_2' ) {
if ( have_posts() )
{
include( PATH_TO_PLUGIN_2 . '/views/single-post_type_2.php' );
die();
}
else
{
$wp_query->is_404 = true;
}
}
}
一旦我注册了插件 2 的 template_redirect 钩子,插件 1 不再工作。
我错过了什么吗?
这样做最好的方法是什么?
最佳解决方案
您应该使用 template_include 过滤器:
add_filter('template_include', 'wpse_44239_template_include', 1, 1);
function wpse_44239_template_include($template){
global $wp_query;
//Do your processing here and define $template as the full path to your alt template.
return $template;
}
template_redirect
是在为渲染模板的输出发送标题之前直接调用的动作。这是一个方便的钩子来做 404 重定向等… 但不应该用于包括其他模板路径,因为 WordPress 这样做本来与’template_include’ 过滤器。
template_include
和 single_template
钩子只处理用于渲染内容的模板的路径。这是调整模板路径的适当位置。
从 @ChipBennett 的评论更新:
single_template
已经被 removed as of 3.4. 改用 {posttype} _template 。
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。