web-dev-qa-db-ja.com

カスタム投稿タイプとtemplate_redirect

表示を処理するために、2つのカスタム投稿タイプ(例: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は機能しなくなります。

私は何かが足りないのですか?

これを行うための最良の方法は何ですか?

9
anderly

これには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_template3.4以降は削除されました 代わりに{posttype} _templateを使用してください。

13
Brian Fegter