Set template based on query in URL

I want to be able to force WordPress to load an page/post based on a query in the URL.

www.mywordpresssite.com/posts/myarticle?template=custom

This URL should load the myarticle post using template custom.php

I don’t even know where to start with this one. Is there a hook I can use to change the template in my theme before it loads?

Any help is appreciated.

1 Answer
1

There are a number of template filters available to override template selection. For a single post you can use the single_template filter:

function wpa_single_template( $template ) {
     if( isset( $_GET['template'] ) ) {
          $template = locate_template( $_GET['template'] . '.php', false );
     }
     return $template;
}
add_filter( 'single_template', 'wpa_single_template' );

Leave a Comment