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

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.