問題描述

我有兩個自定義帖子型別 (例如 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_includesingle_template 鉤子只處理用於渲染內容的模板的路徑。這是調整模板路徑的適當位置。

從 @ChipBennett 的評論更新:

single_template 已經被 removed as of 3.4. 改用 {posttype} _template 。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。