맞춤 게시물 유형 및 template_redirect


9

표시를 처리하기 위해 독립 템플릿 (single-post_type_1.php 및 single-post_type_2.php)으로 리디렉션하려는 두 가지 사용자 지정 게시물 유형 (예 : post_type_1 및 post_type_2)이 있습니다. 각각의 플러그인 폴더에 자체적으로 포함되도록 디스플레이 템플릿을 테마 폴더에 넣고 싶지 않습니다.

서로 영향을주지 않고 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이 더 이상 작동하지 않습니다.

뭔가 빠졌습니까?

가장 좋은 방법은 무엇입니까?

답변:


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_include그리고 single_template후크는 콘텐츠를 렌더링에 사용되는 템플릿의 경로 만 처리합니다. 템플릿 경로를 조정하기에 적합한 위치입니다.

@ChipBennett의 의견 업데이트 :

single_template3.4 에서 삭제되었습니다. 대신 {posttype} _template을 사용하십시오.


따라서 이것은 작동하지만 template_redirect 및 single_template도 작동합니다. 내가 결정한 실제 문제는 '요청'필터에 ​​연결되는 사용자 지정 관리자 열 정렬 기능이 있으며 게시물 유형이 특정 유형 일 때만 $ vars 변수의 수정을 제한하지 않았다는 것입니다. 그러나 template_include 후크에 대해 알게되어 기쁩니다. 여전히 template_redirect, template_include 및 single_template의 차이점이 무엇인지 확실하지 않습니다.
anderly

@anderly 나는 대답을 업데이트했다. 도움이 되었기를 바랍니다.
Brian Fegter

그렇다면 single_template는 어떻습니까? 이 링크 ( codex.wordpress.org/Plugin_API/Filter_Reference/single_template )는 단일 템플릿을 호출 할 때 게시물 또는 페이지의 템플릿을 조정하는 데 사용할 수 있다고 말합니다. 이것이 내가하려는 일입니다. 어쨌든 template_include 또는 single_template 필터를 사용하면 동일한 결과를 얻을 수 있습니다.
anderly

1
single_template은 조건부로 호출되는 것을 제외하고는 동일한 방식으로 작동합니다. 이는 전체 사이트에서 해머 필터를 사용하는 대신 경로 변경을 격리하는 데 도움이됩니다.
Brian Fegter

1
매우 멋진 ... 나는 template_include에 대해 몰랐어요
helgatheviking
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.