MagicWP Docs

Maintenance Mode

Configure and manage WordPress maintenance mode for updates and development

Maintenance Mode

Put your WordPress site in maintenance mode during updates, development, or scheduled maintenance. Ensure visitors see a professional maintenance page while you work on your site.

Maintenance Mode Overview

What is Maintenance Mode?

Maintenance mode temporarily disables your website for visitors while allowing administrators to continue working. It's essential for:

  • Updates: Applying WordPress, plugin, or theme updates
  • Development: Testing new features or designs
  • Migrations: Moving to new servers or platforms
  • Content Updates: Major content restructuring
  • Security Patches: Applying critical security fixes

Maintenance Mode Features

  • Custom Maintenance Page: Professional-looking maintenance message
  • Admin Access: Administrators can still access the site
  • Automatic Deactivation: Set expiration time or manual deactivation
  • SEO Friendly: Proper HTTP status codes for search engines
  • Mobile Responsive: Works on all devices

Enabling Maintenance Mode

Method 1: Built-in WordPress Maintenance Mode

// Enable maintenance mode
$content = '<?php $upgrading = ' . time() . '; ?>';
file_put_contents(ABSPATH . '.maintenance', $content);

// Disable maintenance mode
unlink(ABSPATH . '.maintenance');

Method 2: Plugin-Based Maintenance Mode

// Using a maintenance mode plugin
function enable_maintenance_mode() {
    if (!current_user_can('manage_options') && !is_user_logged_in()) {
        wp_die(
            '<h1>Site Under Maintenance</h1>
            <p>We\'re currently updating our site. Please check back soon!</p>
            <p><a href="mailto:admin@yoursite.com">Contact Us</a></p>',
            'Maintenance',
            array('response' => 503)
        );
    }
}
add_action('get_header', 'enable_maintenance_mode');

Method 3: Using .htaccess

# Enable maintenance mode via .htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000$
RewriteRule ^(.*)$ /maintenance.html [R=503,L]

Custom Maintenance Page

Creating a Professional Maintenance Page

// Create custom maintenance page
function create_custom_maintenance_page() {
    $maintenance_content = '
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Site Under Maintenance</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                margin: 0;
                padding: 0;
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                text-align: center;
            }
            .maintenance-container {
                max-width: 500px;
                padding: 40px;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                backdrop-filter: blur(10px);
            }
            h1 { margin-bottom: 20px; font-size: 2.5em; }
            p { margin-bottom: 30px; font-size: 1.2em; }
            .contact-info { margin-top: 30px; }
        </style>
    </head>
    <body>
        <div class="maintenance-container">
            <h1>🔧 Under Maintenance</h1>
            <p>We\'re currently updating our website to serve you better. We\'ll be back online shortly.</p>
            <p>Expected downtime: 30 minutes</p>
            <div class="contact-info">
                <p>Need urgent assistance?</p>
                <p><a href="mailto:support@yoursite.com">Contact Support</a></p>
            </div>
        </div>
    </body>
    </html>';

    file_put_contents(ABSPATH . 'maintenance.html', $maintenance_content);
}

Advanced Maintenance Page Features

function advanced_maintenance_page() {
    // Check if maintenance mode is enabled
    if (get_option('maintenance_mode_enabled')) {
        $estimated_time = get_option('maintenance_estimated_time');
        $contact_email = get_option('admin_email');

        // Get current time and calculate remaining time
        $start_time = get_option('maintenance_start_time');
        $elapsed = time() - $start_time;
        $remaining = max(0, $estimated_time - $elapsed);

        // Display maintenance page
        include get_template_directory() . '/maintenance-template.php';
        exit;
    }
}
add_action('template_redirect', 'advanced_maintenance_page');

Maintenance Mode Settings

Configuration Options

// Maintenance mode settings
$maintenance_settings = array(
    'enabled' => true,
    'title' => 'Site Under Maintenance',
    'message' => 'We\'re currently updating our site. Please check back soon!',
    'estimated_time' => 1800, // 30 minutes in seconds
    'contact_email' => 'admin@yoursite.com',
    'background_color' => '#f0f0f0',
    'text_color' => '#333333',
    'show_countdown' => true,
    'allow_admin_access' => true,
    'bypass_ips' => array('192.168.1.100', '10.0.0.1')
);

// Save settings
update_option('maintenance_settings', $maintenance_settings);

Countdown Timer

function maintenance_countdown_timer() {
    $settings = get_option('maintenance_settings');
    if (!$settings['show_countdown']) return;

    $start_time = get_option('maintenance_start_time');
    $estimated_time = $settings['estimated_time'];
    $remaining = max(0, ($start_time + $estimated_time) - time());

    $hours = floor($remaining / 3600);
    $minutes = floor(($remaining % 3600) / 60);
    $seconds = $remaining % 60;

    echo "<div class='maintenance-countdown'>
        <p>Estimated time remaining: {$hours}h {$minutes}m {$seconds}s</p>
    </div>";
}

Admin Access During Maintenance

Bypass Maintenance Mode for Administrators

function allow_admin_access_during_maintenance() {
    // Allow administrators
    if (current_user_can('manage_options')) {
        return;
    }

    // Allow specific IP addresses
    $allowed_ips = get_option('maintenance_allowed_ips', array());
    $current_ip = $_SERVER['REMOTE_ADDR'];

    if (in_array($current_ip, $allowed_ips)) {
        return;
    }

    // Allow specific user agents (for crawlers, etc.)
    $allowed_agents = get_option('maintenance_allowed_agents', array());
    $current_agent = $_SERVER['HTTP_USER_AGENT'];

    foreach ($allowed_agents as $agent) {
        if (stripos($current_agent, $agent) !== false) {
            return;
        }
    }

    // Show maintenance page
    show_maintenance_page();
}
add_action('template_redirect', 'allow_admin_access_during_maintenance');

Admin Bar Indicator

function add_maintenance_admin_bar($wp_admin_bar) {
    if (!get_option('maintenance_mode_enabled')) return;

    $wp_admin_bar->add_node(array(
        'id' => 'maintenance-mode',
        'title' => '⚠️ Maintenance Mode Active',
        'href' => admin_url('admin.php?page=maintenance-settings'),
        'meta' => array(
            'class' => 'maintenance-notice'
        )
    ));
}
add_action('admin_bar_menu', 'add_maintenance_admin_bar', 999);

Automated Maintenance Mode

Scheduled Maintenance

function schedule_maintenance_mode($start_time, $duration, $reason) {
    // Schedule maintenance mode activation
    wp_schedule_single_event($start_time, 'activate_maintenance_mode', array(
        'duration' => $duration,
        'reason' => $reason
    ));

    // Schedule deactivation
    wp_schedule_single_event($start_time + $duration, 'deactivate_maintenance_mode');
}

function activate_maintenance_mode_callback($args) {
    update_option('maintenance_mode_enabled', true);
    update_option('maintenance_start_time', time());
    update_option('maintenance_duration', $args['duration']);
    update_option('maintenance_reason', $args['reason']);

    // Send notification
    send_maintenance_notification('started', $args);
}

function deactivate_maintenance_mode_callback() {
    update_option('maintenance_mode_enabled', false);

    // Send notification
    send_maintenance_notification('completed');
}

Conditional Activation

function conditional_maintenance_activation() {
    // Activate during plugin updates
    if (isset($_GET['action']) && $_GET['action'] === 'upgrade-plugin') {
        enable_maintenance_mode('Plugin Update', 300); // 5 minutes
    }

    // Activate during core updates
    if (isset($_GET['action']) && $_GET['action'] === 'do-core-upgrade') {
        enable_maintenance_mode('WordPress Update', 600); // 10 minutes
    }

    // Activate during database operations
    if (isset($_GET['page']) && $_GET['page'] === 'wp-optimize') {
        enable_maintenance_mode('Database Optimization', 180); // 3 minutes
    }
}
add_action('admin_init', 'conditional_maintenance_activation');

SEO Considerations

Proper HTTP Status Codes

function maintenance_mode_http_status() {
    if (get_option('maintenance_mode_enabled') && !current_user_can('manage_options')) {
        header('HTTP/1.1 503 Service Temporarily Unavailable');
        header('Status: 503 Service Temporarily Unavailable');
        header('Retry-After: 3600'); // 1 hour
    }
}
add_action('wp_head', 'maintenance_mode_http_status');

Search Engine Notifications

function notify_search_engines_maintenance() {
    if (get_option('maintenance_mode_enabled')) {
        // Ping search engines about temporary unavailability
        wp_remote_get('https://www.google.com/webmasters/tools/ping?sitemap=' . urlencode(get_site_url() . '/sitemap.xml'));
        wp_remote_get('https://www.bing.com/webmaster/ping.aspx?siteMap=' . urlencode(get_site_url() . '/sitemap.xml'));
    }
}
add_action('maintenance_mode_activated', 'notify_search_engines_maintenance');

Maintenance Mode Logging

Activity Logging

function log_maintenance_activity($action, $details = array()) {
    $log_entry = array(
        'timestamp' => current_time('mysql'),
        'user_id' => get_current_user_id(),
        'action' => $action,
        'ip_address' => $_SERVER['REMOTE_ADDR'],
        'user_agent' => $_SERVER['HTTP_USER_AGENT'],
        'details' => json_encode($details)
    );

    // Store in custom table or use options
    $existing_logs = get_option('maintenance_logs', array());
    $existing_logs[] = $log_entry;

    // Keep only last 100 entries
    if (count($existing_logs) > 100) {
        $existing_logs = array_slice($existing_logs, -100);
    }

    update_option('maintenance_logs', $existing_logs);
}

Maintenance Reports

function generate_maintenance_report() {
    $logs = get_option('maintenance_logs', array());
    $total_maintenance_time = 0;
    $maintenance_count = 0;

    foreach ($logs as $log) {
        if ($log['action'] === 'maintenance_started') {
            $maintenance_count++;
        }
        if ($log['action'] === 'maintenance_completed') {
            // Calculate duration
            $total_maintenance_time += strtotime($log['timestamp']) - strtotime($log['details']['start_time']);
        }
    }

    return array(
        'total_sessions' => $maintenance_count,
        'total_duration' => $total_maintenance_time,
        'average_duration' => $maintenance_count > 0 ? $total_maintenance_time / $maintenance_count : 0
    );
}

Integration with Development Workflow

CI/CD Integration

# Enable maintenance mode before deployment
curl -X POST "https://yoursite.com/wp-admin/admin-ajax.php" \
     -d "action=enable_maintenance&key=YOUR_SECRET_KEY"

# Run deployment
./deploy.sh

# Disable maintenance mode after deployment
curl -X POST "https://yoursite.com/wp-admin/admin-ajax.php" \
     -d "action=disable_maintenance&key=YOUR_SECRET_KEY"

Development Environment Sync

function sync_maintenance_mode_across_environments() {
    // Sync maintenance mode status between staging and production
    $staging_status = get_staging_maintenance_status();
    $production_status = get_option('maintenance_mode_enabled');

    if ($staging_status !== $production_status) {
        // Sync status
        update_option('maintenance_mode_enabled', $staging_status);

        // Log sync action
        log_maintenance_activity('environment_sync', array(
            'from_environment' => 'staging',
            'to_environment' => 'production',
            'new_status' => $staging_status
        ));
    }
}

Troubleshooting

Common Maintenance Mode Issues

Mode Won't Activate

  • Check File Permissions: Ensure web server can create .maintenance file
  • Plugin Conflicts: Disable plugins that might interfere
  • Cache Issues: Clear all caching layers
  • File Path Issues: Verify correct file paths

Admin Access Problems

  • Cookie Issues: Clear browser cookies and cache
  • Session Problems: Check PHP session configuration
  • Role Conflicts: Verify administrator role capabilities
  • IP Restrictions: Check if current IP is blocked

Performance Issues

  • Large Maintenance Files: Optimize maintenance page size
  • Database Load: Monitor database queries during maintenance
  • Memory Usage: Check PHP memory limits
  • Server Resources: Monitor CPU and memory usage

Recovery Procedures

Emergency Deactivation

// Force disable maintenance mode
update_option('maintenance_mode_enabled', false);
unlink(ABSPATH . '.maintenance');

// Clear all caches
wp_cache_flush();

Backup Recovery

# Restore from backup if maintenance caused issues
wp db import backup.sql
tar -xzf wordpress-backup.tar.gz -C /path/to/wordpress

Best Practices

Maintenance Planning

  1. Schedule Wisely: Choose low-traffic periods for maintenance
  2. Communicate: Inform users about scheduled maintenance
  3. Test First: Always test maintenance procedures on staging
  4. Have Rollback: Prepare rollback procedures
  5. Monitor Progress: Track maintenance progress and issues

User Experience

  1. Professional Appearance: Use branded maintenance pages
  2. Clear Communication: Explain what's happening and when
  3. Contact Information: Provide support contact details
  4. Progress Updates: Show progress if maintenance is lengthy
  5. Mobile Friendly: Ensure maintenance page works on mobile

Security Considerations

  1. Access Control: Limit admin access during maintenance
  2. IP Whitelisting: Allow only specific IPs during maintenance
  3. Audit Logging: Log all maintenance activities
  4. Backup Security: Secure backup files during maintenance

Professional maintenance mode management for WordPress sites.

On this page