MagicWP Docs

Automatic Updates

Configure and manage automatic updates for WordPress themes and plugins

Automatic Updates

Keep your WordPress themes and plugins up-to-date automatically with our comprehensive update management system. Ensure security, stability, and access to the latest features.

Update Management Overview

Why Automatic Updates Matter

  • Security: Automatic security patch deployment
  • Stability: Bug fixes and performance improvements
  • Features: Access to new features and enhancements
  • Compliance: Meet security and update requirements
  • Efficiency: Reduce manual maintenance workload

Update Types

  • Security Updates: Critical security patches (highest priority)
  • Bug Fixes: Stability and performance improvements
  • Minor Updates: New features and enhancements
  • Major Updates: Significant changes requiring testing

Configuration Options

Global Update Settings

// Enable automatic updates in wp-config.php
define('WP_AUTO_UPDATE_CORE', true);
define('AUTOMATIC_UPDATER_DISABLED', false);

// Theme and plugin update settings
add_filter('auto_update_theme', '__return_true');
add_filter('auto_update_plugin', '__return_true');

Selective Update Control

// Update specific themes
function auto_update_specific_themes($update, $item) {
    $themes_to_update = array('twentytwentyfour', 'astra', 'generatepress');

    if (in_array($item->theme, $themes_to_update)) {
        return true;
    }

    return $update;
}
add_filter('auto_update_theme', 'auto_update_specific_themes', 10, 2);

// Update specific plugins
function auto_update_specific_plugins($update, $item) {
    $plugins_to_update = array(
        'wordpress-seo/wp-seo.php',
        'contact-form-7/wp-contact-form-7.php'
    );

    if (in_array($item->plugin, $plugins_to_update)) {
        return true;
    }

    return $update;
}
add_filter('auto_update_plugin', 'auto_update_specific_plugins', 10, 2);

Update Scheduling

Time-Based Scheduling

// Schedule updates during low-traffic hours
function schedule_theme_plugin_updates() {
    if (!wp_next_scheduled('automatic_updates_hook')) {
        wp_schedule_event(strtotime('02:00:00'), 'daily', 'automatic_updates_hook');
    }
}
add_action('wp', 'schedule_theme_plugin_updates');

// Execute scheduled updates
function execute_automatic_updates() {
    // Check if updates are available
    wp_maybe_auto_update();

    // Force plugin updates
    $plugin_updates = get_plugin_updates();
    foreach ($plugin_updates as $plugin_file => $plugin_data) {
        if ($plugin_data->update) {
            $result = wp_update_plugin($plugin_file);
            if (is_wp_error($result)) {
                error_log('Plugin update failed: ' . $result->get_error_message());
            }
        }
    }

    // Force theme updates
    $theme_updates = get_theme_updates();
    foreach ($theme_updates as $theme_slug => $theme_data) {
        if ($theme_data->update) {
            $result = wp_update_theme($theme_slug);
            if (is_wp_error($result)) {
                error_log('Theme update failed: ' . $result->get_error_message());
            }
        }
    }
}
add_action('automatic_updates_hook', 'execute_automatic_updates');

Conditional Updates

// Update only on specific conditions
function conditional_updates($update, $item) {
    // Don't update on production during business hours
    if (defined('WP_ENV') && WP_ENV === 'production') {
        $current_hour = date('H');
        if ($current_hour >= 9 && $current_hour <= 17) {
            return false;
        }
    }

    // Skip updates for specific versions
    if (isset($item->new_version) && version_compare($item->new_version, '1.0.0', '<')) {
        return false;
    }

    // Check server resources before updating
    $memory_limit = ini_get('memory_limit');
    if (intval($memory_limit) < 128) {
        return false;
    }

    return $update;
}
add_filter('auto_update_plugin', 'conditional_updates', 10, 2);
add_filter('auto_update_theme', 'conditional_updates', 10, 2);

Update Notifications

Email Notifications

// Send email notifications for updates
function send_update_notifications($type, $successful, $failed) {
    $admin_email = get_option('admin_email');
    $site_name = get_bloginfo('name');

    $subject = "WordPress {$type} Update Report - {$site_name}";

    $message = "Update Report for {$site_name}\n\n";
    $message .= "Update Type: {$type}\n";
    $message .= "Successful Updates: " . count($successful) . "\n";
    $message .= "Failed Updates: " . count($failed) . "\n\n";

    if (!empty($successful)) {
        $message .= "Successfully Updated:\n";
        foreach ($successful as $item) {
            $message .= "- {$item['name']} (v{$item['version']})\n";
        }
        $message .= "\n";
    }

    if (!empty($failed)) {
        $message .= "Failed Updates:\n";
        foreach ($failed as $item) {
            $message .= "- {$item['name']}: {$item['error']}\n";
        }
    }

    wp_mail($admin_email, $subject, $message);
}

// Hook into update completion
add_action('automatic_updates_complete', function($results) {
    $successful = isset($results['plugin']) ? $results['plugin'] : array();
    $failed = isset($results['plugin_failed']) ? $results['plugin_failed'] : array();
    send_update_notifications('Plugin', $successful, $failed);
});

Dashboard Notifications

// Add update notifications to dashboard
function add_update_notifications_to_dashboard() {
    wp_add_dashboard_widget(
        'update_notifications_widget',
        'Update Notifications',
        'display_update_notifications_widget'
    );
}

function display_update_notifications_widget() {
    $updates = get_plugin_updates();
    $theme_updates = get_theme_updates();

    echo '<div class="update-notifications">';
    echo '<h3>Plugin Updates Available</h3>';

    if (!empty($updates)) {
        echo '<ul>';
        foreach ($updates as $plugin_file => $plugin_data) {
            echo "<li>{$plugin_data->Name}: v{$plugin_data->Version} → v{$plugin_data->update->new_version}</li>";
        }
        echo '</ul>';
    } else {
        echo '<p>No plugin updates available</p>';
    }

    echo '<h3>Theme Updates Available</h3>';

    if (!empty($theme_updates)) {
        echo '<ul>';
        foreach ($theme_updates as $theme_slug => $theme_data) {
            echo "<li>{$theme_data->Name}: v{$theme_data->Version} → v{$theme_data->update->new_version}</li>";
        }
        echo '</ul>';
    } else {
        echo '<p>No theme updates available</p>';
    }

    echo '</div>';
}
add_action('wp_dashboard_setup', 'add_update_notifications_to_dashboard');

Backup Integration

Pre-Update Backups

// Create backup before updates
function create_pre_update_backup($item) {
    $backup_name = 'pre_update_backup_' . $item->slug . '_' . time();

    // Create database backup
    $db_backup = wp_db_backup(array(
        'tables' => 'all',
        'compress' => true,
        'filename' => $backup_name . '_db.sql.gz'
    ));

    // Create file backup
    $file_backup = create_theme_plugin_backup($item);

    // Store backup information
    update_option('pre_update_backup_' . $item->slug, array(
        'name' => $backup_name,
        'timestamp' => time(),
        'database' => $db_backup,
        'files' => $file_backup
    ));

    return $backup_name;
}

// Automatic rollback on update failure
function rollback_failed_update($item, $backup_name) {
    $backup_info = get_option('pre_update_backup_' . $backup_name);

    if ($backup_info) {
        // Restore database
        restore_database_backup($backup_info['database']);

        // Restore files
        restore_file_backup($backup_info['files']);

        // Log rollback
        error_log("Rolled back update for {$item->slug} using backup {$backup_name}");
    }
}

Update Testing

Staging Environment Testing

// Test updates in staging first
function test_updates_in_staging($updates) {
    $staging_url = get_option('staging_site_url');

    if (!$staging_url) return false;

    // Send updates to staging for testing
    $response = wp_remote_post($staging_url . '/wp-admin/admin-ajax.php', array(
        'body' => array(
            'action' => 'test_updates',
            'updates' => json_encode($updates),
            'key' => get_option('staging_api_key')
        )
    ));

    if (is_wp_error($response)) {
        return false;
    }

    $result = json_decode(wp_remote_retrieve_body($response), true);
    return $result['success'] ?? false;
}

// Only update production if staging test passes
function conditional_production_update($update, $item) {
    if (defined('WP_ENV') && WP_ENV === 'production') {
        $staging_test_passed = test_updates_in_staging(array($item));

        if (!$staging_test_passed) {
            // Log why update was skipped
            error_log("Skipped production update for {$item->slug} - staging test failed");
            return false;
        }
    }

    return $update;
}
add_filter('auto_update_plugin', 'conditional_production_update', 10, 2);
add_filter('auto_update_theme', 'conditional_production_update', 10, 2);

Monitoring and Logging

Update Activity Logging

// Comprehensive update logging
function log_update_activity($action, $item, $result) {
    global $wpdb;

    $log_data = array(
        'timestamp' => current_time('mysql'),
        'action' => $action,
        'item_type' => isset($item->plugin) ? 'plugin' : 'theme',
        'item_slug' => $item->slug ?? $item->theme ?? $item->plugin,
        'item_name' => $item->name ?? $item->Name ?? 'Unknown',
        'old_version' => $item->version ?? $item->Version ?? 'Unknown',
        'new_version' => $item->update->new_version ?? 'Unknown',
        'result' => $result ? 'success' : 'failed',
        'user_id' => get_current_user_id(),
        'ip_address' => $_SERVER['REMOTE_ADDR'],
        'user_agent' => $_SERVER['HTTP_USER_AGENT']
    );

    $wpdb->insert('wp_update_logs', $log_data);

    // Send notification for failed updates
    if (!$result) {
        wp_mail(
            get_option('admin_email'),
            'Update Failed: ' . $log_data['item_name'],
            "Failed to update {$log_data['item_name']} from v{$log_data['old_version']} to v{$log_data['new_version']}"
        );
    }
}

// Hook into update actions
add_action('upgrader_process_complete', function($upgrader, $hook_extra) {
    if (isset($hook_extra['plugin'])) {
        log_update_activity('plugin_update', (object) array('plugin' => $hook_extra['plugin']), true);
    }
    if (isset($hook_extra['theme'])) {
        log_update_activity('theme_update', (object) array('theme' => $hook_extra['theme']), true);
    }
}, 10, 2);

Performance Considerations

Update Batch Processing

// Process updates in batches to avoid server overload
function batch_update_processing($items, $batch_size = 5) {
    $batches = array_chunk($items, $batch_size);
    $results = array();

    foreach ($batches as $batch) {
        $batch_results = process_update_batch($batch);

        // Wait between batches to prevent server overload
        if (count($batches) > 1) {
            sleep(30); // 30 seconds between batches
        }

        $results = array_merge($results, $batch_results);
    }

    return $results;
}

function process_update_batch($batch) {
    $results = array();

    foreach ($batch as $item) {
        // Check server resources before processing
        if (!check_server_resources()) {
            $results[] = array(
                'item' => $item,
                'status' => 'skipped',
                'reason' => 'insufficient server resources'
            );
            continue;
        }

        $result = update_item($item);
        $results[] = $result;
    }

    return $results;
}

Troubleshooting

Common Update Issues

Memory Limit Errors

// Increase memory limit for updates
function increase_memory_for_updates() {
    if (wp_doing_cron() || (defined('DOING_AJAX') && DOING_AJAX)) {
        ini_set('memory_limit', '512M');
    }
}
add_action('init', 'increase_memory_for_updates');

File Permission Issues

// Check and fix file permissions
function check_update_permissions() {
    $wp_content_dir = WP_CONTENT_DIR;

    // Check if WordPress can write to wp-content
    if (!wp_is_writable($wp_content_dir)) {
        // Attempt to fix permissions
        chmod($wp_content_dir, 0755);

        // Log permission issue
        error_log('Fixed wp-content permissions for updates');
    }

    // Check theme directory
    $theme_dir = get_theme_root();
    if (!wp_is_writable($theme_dir)) {
        chmod($theme_dir, 0755);
        error_log('Fixed theme directory permissions for updates');
    }
}
add_action('admin_init', 'check_update_permissions');

Plugin Conflicts

// Detect and handle plugin conflicts during updates
function detect_update_conflicts($item) {
    $conflicting_plugins = get_option('known_plugin_conflicts', array());

    if (isset($conflicting_plugins[$item->slug])) {
        // Temporarily deactivate conflicting plugins
        $conflicts = $conflicting_plugins[$item->slug];

        foreach ($conflicts as $conflict) {
            if (is_plugin_active($conflict)) {
                deactivate_plugins($conflict);
                update_option('auto_deactivated_' . $conflict, true);
            }
        }
    }
}

function reactivate_plugins_after_update($item) {
    // Reactivate temporarily deactivated plugins
    $all_plugins = get_plugins();

    foreach ($all_plugins as $plugin_file => $plugin_data) {
        $deactivated = get_option('auto_deactivated_' . $plugin_file);
        if ($deactivated) {
            activate_plugin($plugin_file);
            delete_option('auto_deactivated_' . $plugin_file);
        }
    }
}

Best Practices

Update Strategy

  1. Test First: Always test updates in staging environment
  2. Backup Always: Create backups before any updates
  3. Schedule Wisely: Schedule updates during low-traffic periods
  4. Monitor Closely: Monitor updates for any issues
  5. Have Rollback: Prepare rollback procedures

Security Considerations

  1. Verify Sources: Only update from trusted sources
  2. Check Signatures: Verify update package signatures
  3. Monitor Changes: Review changelog for security implications
  4. Access Control: Limit update permissions appropriately

Performance Optimization

  1. Batch Updates: Process updates in manageable batches
  2. Resource Monitoring: Monitor server resources during updates
  3. Caching: Clear caches after updates
  4. Testing: Test site performance after updates

Keep your WordPress themes and plugins secure and up-to-date with automated update management.

On this page