今天在WordPress Answers发现了一段很有用的代码,如何使自定义类型的文章使用page模板展示,其实前几天也写过这样的代码——根据文章所在目录指定post模板,思路相同代码有点差别,我喜欢收集代码,先收集了备用。

function wpa54721_single_template( $templates = '' ){

    // get data for the current post and check type
    $this_post = get_queried_object();
    if( 'my_custom_post_type' == $this_post->post_type ):

        // $templates could be empty, a string, or an array,
        // we need to check and alter it appropriately

        if( !is_array( $templates ) && !empty( $templates ) ):
            // it's a string
            $templates = locate_template( array( 'page.php', $templates ), false );
        elseif( empty( $templates ) ):
            // it's empty
            $templates = locate_template( 'page.php', false );
        else:
            // it's an array
            $new_template = locate_template( array( 'page.php' ) );
            if( !empty( $new_template ) ) array_unshift( $templates, $new_template );
        endif;

    endif;

    return $templates;
}
add_filter( 'single_template', 'wpa54721_single_template' );

代码来自 Make custom post type display as a page