Display page content using multiple templates - WordPress

你说的曾经没有我的故事 提交于 2019-12-06 13:20:55

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;
}
?>
eddiemoya

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!