自定义帖子类型和template_redirect


9

我有两种自定义帖子类型(例如post_type_1和post_type_2),我想将其重定向到独立模板(single-post_type_1.php和single-post_type_2.php)来处理它们的显示。我不想将显示模板放在主题文件夹中,因为我希望它们独立包含在各自的插件文件夹中。

如何让他们每个人注册一个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便不再起作用。

我想念什么吗?

做这个的最好方式是什么?

Answers:


13

您应该为此使用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_includesingle_template挂钩仅处理用于呈现内容的模板的路径。这是调整模板路径的适当位置。

@ChipBennett的评论更新:

single_template从3.4开始已被删除。请改用{posttype} _template。


因此,这可以工作,但事实证明template_redirect和single_template也可以工作。我确定的真正问题是,我有一个自定义的admin列排序功能,该功能可以连接到“请求”过滤器,并且我并没有将$ vars变量的修改限制为仅在特定类型的帖子类型时使用。但是,我很高兴了解template_include挂钩。仍然不确定虽然template_redirect,template_include和single_template有什么区别。
2012年

@anderly我更新了答案。希望这可以帮助。
Brian Fegter'3

那么,single_template呢?此链接(codex.wordpress.org/Plugin_API/Filter_Reference/single_template)表示,当调用单个模板时,可用于调整帖子或页面的模板。这就是我想要做的。在任何情况下,使用template_include或single_template过滤器都可以工作,并且看起来可以完成相同的任务。
Anderly 2012年

1
single_template的工作方式相同,只是有条件地调用它。这有助于隔离路径更改,而不是在整个站点上使用锤式滤波器。
Brian Fegter'3

1
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.