Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

If I visit a page on my WordPress site, WP goes and determines what template file it should use based on the template hierarchy.

If I'm doing some logic checking in the hook init and say my conditions are met, how do I tell WordPress to load a template file of my choosing, not the one WordPress would normally dish up?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

Can you perform the logic on the template_include filter? Else, you could set a global/constant and use that in template_include to serve up the appropriate template.

The template_include filter filers the path to the template file to be included. To avoid errors you should check if the template exists - locate_template does this for theme/child-theme files.

add_filter("template_include", "sc_redirect_properties_to_registration");
function sc_redirect_properties_to_registration( $template )
{
    if( is_user_logged_in() && ! is_page("the-properties") )
        return $template;

    //You could include templates from plugins
    //$template = plugin_dir_path(__FILE__).'templates/plugin-template.php';

    //Best to check the template exists. With **theme/child-theme** templates
    // you can do this with locate_template.
    return locate_template('template-registration.php');
}
share|improve this answer
    
Can you add an example of using this filter to change the choice of template file? The codex has a blank page on this filter. –  Brady Jun 19 '12 at 15:21
    
Thank you very much –  Brady Jun 19 '12 at 15:38
add comment

I suppose you could use some conditions like this:

if(is_front_page()){
    // Home page layout
} elseif(is_page()){
    // General page layout
    if(is_page('contact')){
        // Page layout specific to the contact page
    } elseif(is_page('about')){
        // Page layout specific to the about page
    }
}

Then obtain parts of your template depending on the section of your website using get_template_part();

share|improve this answer
    
Sorry Michael I think you have misunderstood my question. I've edited my question to hopefully be a little more clearer to put across what I am after. –  Brady Jun 19 '12 at 15:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.