Programatically switch page template?

I want to build a very simple toggle for taking my site down into a maintenance mode. To do that, I want to add a admin area to define a template that is the maintenance page, and allow that page to override the database defined template when maintenance mode is switched on.

How can I change the theme template called for each page, WITHOUT affecting the database?

Related posts

Leave a Reply

1 comment

  1. you can use template_redirect action hook to php include your maintenance mode template file using a simple option in options database.

    When you turn maintenance mode on add an option for example:

    add_option('maintenance_mode_on');
    

    then with this code you check if that option is set and if so you redirect to your desired template file:

    function custom_maintenance_mode_template_redirect() {
        global $wp;
        if(get_option('maintenance_mode_on')){
            status_header(200); // a 404 code will not be returned in the HTTP headers if the page does not exists
    
            include(TEMPLATEPATH . "/Custom_template.php"); // include the corresponding template
            die();
        }
    }
    add_action( 'template_redirect', 'custom_maintenance_mode_template_redirect' );
    

    Then when you turn maintenance mode off delete that option :

    delete_option('maintenance_mode_on');
    

    Update

    If you want to effect the body_class() you can use body_class filter hook:

    function custom_body_class($classes){
        if(get_option('maintenance_mode_on')){
                $n_classes[] = "maintenance";
            return $n_classes;
        } else {
            return $classes;
        }
    }
    
    add_filter('body_class', 'custom_body_class');
    

    This will change the body_class() to output maintenance when maintenance mode is turned on.