Load custom template for specific GET parameter

Just found an pretty straightforward solution for this problem:

add_action( 'template_include', 'account_page_template' );

function account_page_template( $template ) {

    if( isset( $_GET[ 'account' ] ) ) {

        return locate_template( array( 'account.php' ) );

    }

    return $template;

}

But as it seems only natural to use some kind of permalink stucture for these kind of things here is a part of my final code that make urls structures like example.com/account/user_name possible:

// Register to query vars

add_filter( 'query_vars', 'add_query_vars');


function add_query_vars( $vars ) {

    $vars[] = 'account';

    return $vars;

}


// Add rewrite endpoint


add_action( 'init', 'account_page_endpoint' );

function account_page_endpoint() {

    add_rewrite_endpoint( 'account', EP_ROOT );

}



// Load template

add_action( 'template_include', 'account_page_template' );

function account_page_template( $template ) {

    if( get_query_var( 'account', false ) !== false ) {

        return locate_template( array( 'account.php' ) );

    }

    return $template;

}

In the acccount.php template you can fetch the parameter value like this:

$user_name = get_query_var( 'account', false );