PAGE_TEMPLATE在2个模板+2个相同帖子的固定链接之间切换

时间:2014-03-14 作者:James Greig

我想用这个page_template template 来自WP论坛,目的与原作者相同:

我正在尝试为一篇文章使用两个单独的永久链接/模板-每个都提供不同的文章视图(通过不同的模板)。http://example.com/category/post-name -> 使用模板1。phphttp://example.com/category/post-name/details -> 使用模板2。php

我已经根据线程中讨论的更改修改了代码,但我的备用模板(用于自定义帖子类型)没有加载-/post name/detail只是重定向到/post name/。

有什么想法吗?

// Add \'detail\' to the permalink structure / query string 
function detail_rewrite_rules( $rules ) {
    $newrules = array();
    $newrules[\'(.+?)/([^/]+)(/[0-9]+)?/detail/?$\'] = \'index.php?category_name=$matches[1]&name=$matches[2]&page=$matches[3]&detail=1\'; 

    return $newrules + $rules;
}
add_filter( \'rewrite_rules_array\',\'detail_rewrite_rules\' );

function detail_flush_rules(){
    $rules = get_option( \'rewrite_rules\' );

    if ( ! isset( $rules[\'(.+?)/([^/]+)(/[0-9]+)?/detail/?$\'] )   ) {

        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
}
add_action( \'init\',\'detail_flush_rules\' );

// Open up \'detail\'
function detail_queryvars( $qvars ) {
  $qvars[] = \'detail\';
  return $qvars;
}
add_filter(\'query_vars\', \'detail_queryvars\' );

// Switch between templates
function filter_single_template($template){

    $object = get_queried_object();
    $templates = array();

    /* If detail is in the query string, create a list of templates to use */
    // if($_GET[\'detail\']) {
    // if( get_query_var(\'detail\') ) {
    global $wp_query;
    if ( $wp_query->query_vars[\'detail\'] ) {    
        echo "<script>console.log(\'Detail template activated\');</script>";
        $templates[] = "single-photos-detail.php";
        // $templates[] = "detail-single.php";
        // $templates[] = "detail-single-{$object->post_type}.php";
    }

    /* If one of our custom detail templates exists, return it.
     * Otherwise return the original template
     */
    $templateSwitch = locate_template($templates);
    return (!empty($templateSwitch)) ? locate_template($templates) : $template;
}
add_filter(\'page_template\', \'filter_single_template\');

1 个回复
最合适的回答,由SO网友:Milo 整理而成

WordPress的功能更简单,add_rewrite_endpoint. 此外,单个帖子模板的过滤器为single_template, page_templatepage 岗位类型。

function wpd_detail_endpoint(){
    add_rewrite_endpoint( \'detail\', EP_PERMALINK );
}
add_action( \'init\', \'wpd_detail_endpoint\' );

function wpd_detail_template( $template = \'\' ) {
    global $wp_query;
    if( ! array_key_exists( \'detail\', $wp_query->query_vars ) ) return $template;

    $template = locate_template( \'single-photos-detail.php\' );
    return $template;
}
add_filter( \'single_template\', \'wpd_detail_template\' );
这假设模板存在,您可能需要在原始函数中进行一些额外的检查。

结束

相关推荐

Admin sidebar customization

我的新客户wordpress站点在管理侧栏中没有插件、外观或任何其他默认项。谁能告诉我这些是怎么出现的吗。该站点正在主站点的子目录中运行。它有自己的wordpress安装。主题是前面的rttheme16。提前谢谢。