michaelmcgurk
michaelmcgurk

Reputation: 6509

Display page content using multiple templates - WordPress

Is it possible to have a page like: www.site.com/page/

and show different templated versions using, say:

www.site.com/page/?template=default

www.site.com/page/?template=archive

...?

So it retrieves the same page content but displays it differently.

Is this possible with WordPress? Is it standard or would need some tomhackery to do this?

Thank you

Upvotes: 2

Views: 2250

Answers (2)

eddiemoya
eddiemoya

Reputation: 7478

I answered a similar question a moment ago.

Manually set template using PHP in WordPress

The answer above should work, but the use of TEMPLATEPATH, I think is not ideal, it also seems to not take advantage of what WordPress is already doing to select a template.

function filter_page_template($template){

        /* Lets see if 'template is set' */
        if( isset($_GET['template']) ) {

            /* If so, lets try to find the custom template passed as in the query string. */
            $custom_template = locate_template( $_GET['template'] . '.php');

            /* If the custom template was not found, keep the original template. */
            $template = ( !empty($custom_template) ) ?  $custom_template : $template;
        }

        return $template;
}
add_filter('page_template', 'filter_page_template');

Doing it this way, you don't need to add a new line for every template you want to be able to specify. Also, you take advantage of the existing template hierarchy, and account for the possibility that a non-existant template was entered.

I would point out that you should do some validation against the $_GET['template'] value before using it, but also that you might want to keep a running list to check against, so that they cant simply use any old template.

Upvotes: 4

Gabriel Roth
Gabriel Roth

Reputation: 1040

Create a 'master' template and assign it to your page. The master template doesn't contain any layout information—just a set of conditional include statements that selects the 'real' template based on the GET variable. The master template might look something like this:

<?php
switch ($_GET["template"]) {
    case "foo":
        include(TEMPLATEPATH . "/foo.php");
        break;
    case "bar":
        include(TEMPLATEPATH . "/bar.php");
        break;
    case "baz":
        include(TEMPLATEPATH . "/baz.php");
        break;
    default:
        include(TEMPLATEPATH . "/default_template.php");
        break;
}
?>

Upvotes: 2

Related Questions