1

How is it possible to load a different template file when a specific GET parameter is set?

I want to create an account details page. So when the account parameter is set there should be loaded for example account.php instead of index.php.

The urls would look something like this: example.com?account=user_name

3

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 );
  • 1
    Isn’t it so that your code uses query var and not GET request parameter? I’m pretty sure there will be no query bar automatically created based on GET param, unless you register your custom query var...? – Krzysiek Dróżdż Mar 30 '18 at 9:48
  • 1
    @KrzysiekDróżdż yeah well thats right. Im already a bit further and using an rewrite endpoint and registering it as query var seems only natural in this scenario … concerning the given question it would correct to check the GET parameter and not a query var. Ive changed that ;) – GDY Mar 30 '18 at 12:39

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.