admin管理员组

文章数量:1300029

Let's say i have a custom post type names "Projects", is it possible to have two template like :

  • Minimal template (with a few info about the projet)
  • Complete template (all the info)

And the template is selected according the url :

site/minimal-template/project-1 or site/complete-template/project-1

Is it possible ? Thanks

Let's say i have a custom post type names "Projects", is it possible to have two template like :

  • Minimal template (with a few info about the projet)
  • Complete template (all the info)

And the template is selected according the url :

site/minimal-template/project-1 or site/complete-template/project-1

Is it possible ? Thanks

Share Improve this question asked Mar 23, 2021 at 9:48 LinkrefLinkref 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

Use the query_vars filter to add a new query variable to store the template version (minimal / complete).

add_filter( 'query_vars', 'se385568_query_vars' );
function se385568_query_vars( $vars )
{
    $vars[] = 'tpl';
    return $vars;
} 

Add a rewrite rule (codex) to recognize the new link format and set the newly created query variable

add_action( 'init', 'se385568_rewrite_rules' );
function se385568_rewrite_rules()
{
    $cpt_slug = 'projects';
    add_rewrite_rule(
        "^(minimal|complete)-template/([^/]+)(?:/([0-9]+))?/?$",
        'index.php?'. $cpt_slug .'=$matches[2]&tpl=$matches[1]&page=$matches[3]',
        'top'
    );
}

Use the template_include filter to change the loaded template based on your query variable.

add_filter( 'template_include', 'se385568_project_template', 90 );
function se385568_project_template()
{
    $qv = get_query_var('tpl', null);
    if ( empty($qv)  )
        return $template;
    
    //
    // check $qv and return path to the appropriate file
    //
    $template =  dirname(__FILE__) . '/se385568_minimal_project.php';

    return $template;
}

Remember to refresh the rewrite rules (Dashboard -> Settings -> Permalinks -> Save) after adding the code.

本文标签: customization2 Templates 1 custom post type according url