0

Is there some way to change the page template dynamically using just a url I wanna use it in a demo theme, so for example when the user enters a particular URL ending with for example

?custom_page_template

it changes the template on the fly?

Could this technique be used to change the theme (or maybe a child theme) on the fly just for demo purpose?

1 Answer 1

0

Filter pre_option_stylesheet. Sample code, not tested:

add_filter( 'pre_option_stylesheet', 'wpse_100854_switch_stylesheet' );

function wpse_100854_switch_stylesheet( $false )
{
    if ( empty ( $_GET['theme'] )
        return $false;

    $themes = wp_get_themes( array( 'allowed' => true ) );

    if ( isset ( $themes[ $_GET['theme'] ] ) )
        return $_GET['theme'];

    return $false;
}

The URL should look like example.com/?theme=theme_directory_slug.

To change just the template for a specific page, hook into template_include:

add_filter( 'template_include', 'wpse_100854_switch_template' );

function wpse_100854_switch_template( $template )
{
    if ( empty ( $_GET['template'] )
            return $false;

    // do not allow to break out of the directory
    $new  = ltrim( $_GET['template'], '.' ); 
    $path = get_template_directory() . "/templates/$new.php";

    if ( file_exists( $path ) )
        return $path;

    return $template;
}

Now add a directory templates to your theme. When someone requests example.com/?template=blue and the template blue.php exists in the special directory, it will be used.

14
  • Thanks for mentioning the function, I have found these links, could be useful: codex.wordpress.org/Plugin_API/Filter_Reference/… shibashake.com/wordpress-theme/switch_theme-vs-theme-switching Commented May 27, 2013 at 10:28
  • Now, I have used this function, How can I use it? - I mean now what is the URL I am after? Commented May 27, 2013 at 10:40
  • @CapitalH.ir See my update.
    – fuxia
    Commented May 27, 2013 at 10:42
  • Why do you use 'pre_option_stylesheet' instead of 'pre_option_template'? Also, could you not use the action 'template_redirect'?
    – user27457
    Commented May 27, 2013 at 10:47
  • @MagentaCuda This filter runs as early as possible. template_redirect is way too late.
    – fuxia
    Commented May 27, 2013 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.