How can I have two different urls for the same page that load two different templates?

You could accomplish this with a rewrite endpoint and a template filter.

First, register a new rewrite endpoint for the page post type:

function wpd_app_view_rewrite_endpoint() {
    add_rewrite_endpoint( 'app-view', EP_PAGES );
}
add_action( 'init', 'wpd_app_view_rewrite_endpoint' );

Don’t forget to flush rewrite rules after adding this (or just visit the Permalinks > Settings page to do this without code).

Now you will be able to add app-view/ on the end of any page permalink URL, for example, your page will be domain.com/messages/app-view/.

The next step is to detect when app-view/ is present, and load a different template in that case. For the page post type we use the page_template filter:

function wpd_app_view_page_template( $template ) {
    global $wp_query;
    if( isset( $wp_query->query_vars['app-view'] )  ) {
        $template = locate_template( array( 'app-view-template.php' ) );
    }
    return $template;
}
add_filter( 'page_template', 'wpd_app_view_page_template' );

This checks if query_vars['app-view'] is set in the global $wp_query object, and loads the app-view-template.php template in this case. This will only be true when the app-view rewrite rule matches the current request.

Leave a Comment