1

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.com/minimal-template/project-1 or site.com/complete-template/project-1

Is it possible ? Thanks

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.