Manually set template using PHP in WordPress

2019-08-01 10:57发布

I'm designing a new template to replace an existing one. The template is called featured.php and I'm going to be replacing it with featured-new.php

I want to pass the variable "new" in the querystring, then if the new variable is present it'll using the featured-new.php file.

How can I do this? Is there a tag to tell a page to use a specified template?

3条回答
一纸荒年 Trace。
2楼-- · 2019-08-01 11:16

I think that the easiest way to do this would be to if/else the current themplate to include new templete or not

in featured.php

if($_GET['show'] == 'new')
{
   include('featured-new.php');
}
else
{
   //this is the full featured.php code
}

You may also find more help in WordPress Template Hierarchy

查看更多
地球回转人心会变
3楼-- · 2019-08-01 11:22

I would use theme switcher plugins such as this one, then customize whether present it only from URL or switch on the layout.

Also, take a look at this: Theme Switching

查看更多
看我几分像从前
4楼-- · 2019-08-01 11:33

I am assuming this is a Page Template, is that right? Meaning that it has a comment 'Template Name: ' at the top, and its used when a Page comes up, and the name has been chosen from the 'Page Template' menu in the editor. If thats the case, then were on the same... page (pun was unavoidable.)

If thats the case, you need to filter 'page_template'.

function filter_page_template($template){

    /**
     * Lets see if the current template is featured.php, 
     * and if 'new' is set in the query string
     */
    if(isset($_GET['new']) && $template == locate_template('featured.php')) {

        /** 
         * If so, we'll set the custom template name... 
         * You can skip this temporary variable and just pass this
         * directly to 'locate_template()'.
         */
        $new_template = 'featured-new.php';

        /*... and now we use locate_template to find the actual path and return that. */
        return locate_template($new_template);

    } else {

        /**
         * Otherwise, if 'new' is not set 
         * or the current template is not 'featured.php',
         * We should just return the original $template value undisturbed. 
         */
        return $template;
    }
}
add_filter('page_template', 'filter_page_template');

I don't understand how you wanted to use 'new', sounded like to wanted a query string parameter that was called new, and see if it was just set at all. So thats what I did. If you meant something different you'll need to change that bit of logic accordingly.

查看更多
登录 后发表回答