Using two permalinks for one post

I’ll preface this by saying I think it makes much more sense to have play appended to the end of the permalink, which you could easily achieve with add_rewrite_endpoint, but in the interest of answering the question as it was asked…

First you’ll need to add a query var that you’ll later check to know when to load your other template:

function wpd_query_var( $query_vars ){
    $query_vars[] = 'is_play';
    return $query_vars;
}
add_filter('query_vars', 'wpd_query_var');

Next you’ll need a rewrite rule to handle incoming requests and set the proper query for your single post, and also set the above query var flag to load your template later.

function wpd_post_rewrite(){
    add_rewrite_rule(
        'play/([^/]+)/?$',
        'index.php?name=$matches[1]&is_play=1',
        'top'
    );
}
add_action( 'init', 'wpd_post_rewrite' );

Lastly, the filter to check if the query var is set and load the other template in that case:

function wpd_play_template( $single_template ){
    global $wp_query;
    if ( isset( $wp_query->query_vars['is_play'] ) ) {
        $single_template = locate_template( 'play_template.php', false );
    }
    return $single_template;
}
add_filter( 'single_template', 'wpd_play_template' );

Remember to flush your rewrite rules after changing them so the new rule gets picked up.

Leave a Comment