Manually set template using PHP in WordPress

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.

Read More

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

Related posts

Leave a Reply

3 comments

  1. 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.

  2. 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