MagicWP Docs

Cache Management

Comprehensive caching solutions for optimal WordPress performance

Cache Management

Optimize your WordPress site's performance with comprehensive caching strategies. Learn to implement and manage various caching layers for maximum speed and efficiency.

Caching Fundamentals

What is Caching?

Caching stores frequently accessed data in temporary storage for faster retrieval. In WordPress, this reduces server load and improves user experience by serving content quickly.

Types of Caching

Browser Caching

  • Leverages browser storage to cache static assets
  • Reduces server requests for images, CSS, JavaScript
  • Improves perceived performance with instant loading
  • Configurable expiration times for different content types

Page Caching

  • Caches entire HTML pages for faster delivery
  • Reduces PHP execution and database queries
  • Handles dynamic content with cache variations
  • Supports cache invalidation for content updates

Object Caching

  • Caches database queries and complex objects
  • Reduces database load significantly
  • Speeds up plugin operations and custom queries
  • Supports persistent storage with Redis/Memcached

Database Caching

  • Caches query results in memory
  • Reduces database server load
  • Improves query performance for complex operations
  • Handles cache invalidation automatically

WordPress Caching Setup

Built-in WordPress Caching

Enable Object Caching

// Enable object caching in wp-config.php
define('WP_CACHE', true);

// Optional: Set cache key salt for multisite
define('WP_CACHE_KEY_SALT', 'your-unique-salt');

Transient API Usage

// Cache expensive operations
function get_expensive_data($key) {
    $cached_data = get_transient('expensive_data_' . $key);

    if (false === $cached_data) {
        // Perform expensive operation
        $cached_data = perform_expensive_calculation($key);

        // Cache for 1 hour
        set_transient('expensive_data_' . $key, $cached_data, HOUR_IN_SECONDS);
    }

    return $cached_data;
}

// Clear specific transients
function clear_expensive_cache($key) {
    delete_transient('expensive_data_' . $key);
}

WP Super Cache Configuration

// WP Super Cache settings
define('WPCACHEHOME', '/path/to/wp-content/plugins/wp-super-cache/');

// Enable advanced features
define('WP_CACHE_MAKE_LOCKED_DOWN', true); // Lock down permissions
define('WP_CACHE_MAINTENANCE_MODE', false); // Maintenance mode
define('WP_CACHE_FRONT_PAGE_CHECKS', true); // Front page specific caching

W3 Total Cache Setup

// W3 Total Cache configuration
define('W3TC_CONFIG_DATABASE', true);
define('W3TC_CONFIG_FILE', true);
define('W3TC_CONFIG_EDGE_MODE', false);

// Enable specific caches
define('W3TC_PAGE_CACHE_ENABLED', true);
define('W3TC_OBJECT_CACHE_ENABLED', true);
define('W3TC_DATABASE_CACHE_ENABLED', true);

WP Rocket Configuration

// WP Rocket optimizations
define('WP_ROCKET_WHITE_LABEL_FOOTPRINT', true); // Hide footer link
define('WP_ROCKET_WHITE_LABEL_ACCOUNT', true); // White label account

// Cache settings
define('WP_ROCKET_CACHE_MOBILE', true);
define('WP_ROCKET_CACHE_SSL', true);
define('WP_ROCKET_CACHE_REJECT_URI', '/checkout/*,/cart/*'); // Exclude pages

Advanced Caching Strategies

Multi-Layer Caching

CDN Integration

// CDN configuration
define('CDN_DOMAIN', 'cdn.yourdomain.com');
define('CDN_CONTENT_TYPES', 'jpg|jpeg|png|gif|css|js|ico|svg');
define('CDN_EXCLUDE', 'wp-admin|wp-login');

// URL rewriting for CDN
function cdn_rewrite_url($url) {
    $content_types = explode('|', CDN_CONTENT_TYPES);
    $exclude_patterns = explode('|', CDN_EXCLUDE);

    // Skip excluded patterns
    foreach ($exclude_patterns as $pattern) {
        if (strpos($url, $pattern) !== false) {
            return $url;
        }
    }

    // Check file extension
    $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
    if (in_array($extension, $content_types)) {
        return str_replace(site_url(), 'https://' . CDN_DOMAIN, $url);
    }

    return $url;
}
add_filter('wp_get_attachment_url', 'cdn_rewrite_url');

Reverse Proxy Caching

# Nginx reverse proxy caching
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m;

server {
    location / {
        proxy_pass http://wordpress_backend;
        proxy_cache my_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout invalid_header updating;
    }
}

Database Query Caching

Custom Query Caching

// Cache custom database queries
function cache_custom_query($query, $cache_key, $expiration = 3600) {
    $cached_result = wp_cache_get($cache_key, 'custom_queries');

    if (false === $cached_result) {
        global $wpdb;
        $cached_result = $wpdb->get_results($query);
        wp_cache_set($cache_key, $cached_result, 'custom_queries', $expiration);
    }

    return $cached_result;
}

// Usage example
$popular_posts = cache_custom_query(
    "SELECT * FROM {$wpdb->posts} WHERE post_status = 'publish' ORDER BY comment_count DESC LIMIT 10",
    'popular_posts',
    1800 // 30 minutes
);

Prepared Statement Caching

// Cache prepared statements
class CachedPreparedStatement {
    private $cache_group = 'prepared_statements';
    private $expiration = 3600;

    public function get_prepared_results($sql, $params = array()) {
        $cache_key = md5($sql . serialize($params));

        $cached = wp_cache_get($cache_key, $this->cache_group);
        if (false !== $cached) {
            return $cached;
        }

        global $wpdb;
        $prepared = $wpdb->prepare($sql, $params);
        $results = $wpdb->get_results($prepared);

        wp_cache_set($cache_key, $results, $this->cache_group, $this->expiration);

        return $results;
    }
}

Cache Invalidation Strategies

Automatic Invalidation

Post Update Hook

// Clear cache when posts are updated
function clear_post_cache($post_id) {
    // Clear specific post cache
    wp_cache_delete('post_' . $post_id, 'posts');

    // Clear related caches
    wp_cache_delete('recent_posts', 'homepage');
    wp_cache_delete('popular_posts', 'homepage');

    // Clear page cache if using plugins
    if (function_exists('wp_cache_clear_cache')) {
        wp_cache_clear_cache();
    }
}
add_action('save_post', 'clear_post_cache');

Comment Update Hook

// Clear cache when comments are added/updated
function clear_comment_cache($comment_id, $comment) {
    $post_id = $comment->comment_post_ID;

    // Clear post comment cache
    wp_cache_delete('post_comments_' . $post_id, 'comments');
    wp_cache_delete('comment_count_' . $post_id, 'comments');

    // Clear general comment caches
    wp_cache_delete('recent_comments', 'comments');
}
add_action('wp_insert_comment', 'clear_comment_cache', 10, 2);
add_action('wp_update_comment', 'clear_comment_cache', 10, 2);

Manual Cache Clearing

Admin Interface for Cache Management

// Add cache management to admin bar
function add_cache_management_menu($wp_admin_bar) {
    $wp_admin_bar->add_node(array(
        'id' => 'cache-management',
        'title' => 'Cache Management',
        'href' => admin_url('admin.php?page=cache-management'),
        'meta' => array(
            'class' => 'cache-management-menu'
        )
    ));

    $wp_admin_bar->add_node(array(
        'id' => 'clear-cache',
        'parent' => 'cache-management',
        'title' => 'Clear All Cache',
        'href' => wp_nonce_url(admin_url('admin.php?action=clear_all_cache'), 'clear_cache'),
        'meta' => array(
            'class' => 'clear-cache-menu'
        )
    ));
}
add_action('admin_bar_menu', 'add_cache_management_menu', 999);

Cache Clearing Functions

// Clear all cache types
function clear_all_caches() {
    // Clear WordPress object cache
    wp_cache_flush();

    // Clear transients
    global $wpdb;
    $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_%'");

    // Clear plugin caches
    if (function_exists('wp_super_cache_flush')) {
        wp_super_cache_flush(); // WP Super Cache
    }

    if (function_exists('w3tc_flush_all')) {
        w3tc_flush_all(); // W3 Total Cache
    }

    if (function_exists('wp_cache_clear_cache')) {
        wp_cache_clear_cache(); // WP Rocket
    }

    // Clear opcode cache if available
    if (function_exists('opcache_reset')) {
        opcache_reset();
    }
}

Performance Monitoring

Cache Performance Metrics

Cache Hit/Miss Ratio

// Track cache performance
function track_cache_performance() {
    static $hits = 0;
    static $misses = 0;

    // Hook into cache operations
    add_action('wp_cache_get', function($key, $group, $found) {
        if ($found) {
            $hits++;
        } else {
            $misses++;
        }
    }, 10, 3);

    // Calculate ratio
    $total = $hits + $misses;
    if ($total > 0) {
        $hit_ratio = ($hits / $total) * 100;
        error_log("Cache Hit Ratio: {$hit_ratio}% (Hits: {$hits}, Misses: {$misses})");
    }
}
add_action('wp_loaded', 'track_cache_performance');

Cache Size Monitoring

// Monitor cache size and cleanup
function monitor_cache_size() {
    $cache_dir = WP_CONTENT_DIR . '/cache/';

    if (is_dir($cache_dir)) {
        $cache_size = get_directory_size($cache_dir);

        // Log cache size
        error_log("Cache Size: " . size_format($cache_size));

        // Auto cleanup if too large (1GB)
        if ($cache_size > 1073741824) {
            clean_cache_directory($cache_dir, 50); // Remove 50% oldest files
        }
    }
}

function get_directory_size($directory) {
    $size = 0;
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
        $size += $file->getSize();
    }
    return $size;
}

Advanced Caching Techniques

Conditional Caching

User-Specific Caching

// Cache different versions for logged-in users
function get_user_specific_cache_key($base_key) {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        return $base_key . '_user_' . $user_id;
    }

    return $base_key . '_guest';
}

// Usage
$cache_key = get_user_specific_cache_key('homepage_content');
$content = wp_cache_get($cache_key, 'page_cache');

Device-Specific Caching

// Cache different versions for mobile/desktop
function get_device_cache_key($base_key) {
    if (wp_is_mobile()) {
        return $base_key . '_mobile';
    }

    return $base_key . '_desktop';
}

// Usage
$cache_key = get_device_cache_key('product_listing');
$products = wp_cache_get($cache_key, 'product_cache');

Cache Warming

Automatic Cache Warming

// Warm up cache for important pages
function warm_up_cache() {
    $important_pages = array(
        home_url('/'),
        home_url('/about/'),
        home_url('/contact/'),
        home_url('/products/')
    );

    foreach ($important_pages as $url) {
        // Make HTTP request to warm cache
        wp_remote_get($url, array(
            'timeout' => 10,
            'redirection' => 5,
            'httpversion' => '1.1',
            'user-agent' => 'Cache Warmer',
            'blocking' => false // Non-blocking request
        ));
    }
}

// Schedule cache warming
if (!wp_next_scheduled('warm_up_cache')) {
    wp_schedule_event(time(), 'hourly', 'warm_up_cache');
}
add_action('warm_up_cache', 'warm_up_cache');

Troubleshooting Cache Issues

Common Cache Problems

Cache Not Working

// Debug cache functionality
function debug_cache_operations() {
    // Test basic cache operations
    wp_cache_set('test_key', 'test_value', 'test_group', 300);
    $cached_value = wp_cache_get('test_key', 'test_group');

    if ($cached_value === 'test_value') {
        error_log('Basic cache operations working');
    } else {
        error_log('Cache operations failed');
    }

    // Check cache backend
    if (wp_using_ext_object_cache()) {
        error_log('Using external object cache');
    } else {
        error_log('Using default WordPress object cache');
    }
}
add_action('wp_loaded', 'debug_cache_operations');

Stale Cache Content

// Force cache refresh for debugging
function force_cache_refresh() {
    // Clear all caches
    wp_cache_flush();

    // Clear page cache
    if (function_exists('wp_cache_clear_cache')) {
        wp_cache_clear_cache();
    }

    // Clear CDN cache if applicable
    clear_cdn_cache();

    // Regenerate important caches
    warm_up_cache();
}

Cache Conflicts

// Detect cache plugin conflicts
function detect_cache_conflicts() {
    $active_plugins = get_option('active_plugins');
    $cache_plugins = array(
        'wp-super-cache/wp-cache.php',
        'w3-total-cache/w3-total-cache.php',
        'wp-rocket/wp-rocket.php',
        'wp-fastest-cache/wpFastestCache.php'
    );

    $active_cache_plugins = array_intersect($cache_plugins, $active_plugins);

    if (count($active_cache_plugins) > 1) {
        error_log('Multiple cache plugins detected: ' . implode(', ', $active_cache_plugins));
        error_log('This may cause conflicts. Consider using only one cache plugin.');
    }
}
add_action('admin_init', 'detect_cache_conflicts');

Cache Security Considerations

Cache Poisoning Prevention

// Prevent cache poisoning attacks
function secure_cache_keys($key) {
    // Sanitize cache keys to prevent injection
    $key = sanitize_key($key);

    // Add user context to prevent cache poisoning
    if (is_user_logged_in()) {
        $key .= '_user_' . get_current_user_id();
    }

    // Add session context for additional security
    $session_id = session_id();
    if ($session_id) {
        $key .= '_session_' . substr($session_id, 0, 8);
    }

    return $key;
}

// Usage
$secure_key = secure_cache_keys('user_preferences');
$user_prefs = wp_cache_get($secure_key, 'user_data');

Cache Content Validation

// Validate cached content integrity
function validate_cached_content($cached_data, $validation_key) {
    if (!is_array($cached_data) || !isset($cached_data['content'])) {
        return false;
    }

    // Check content hash for integrity
    $content_hash = md5(serialize($cached_data['content']));
    $stored_hash = get_transient($validation_key . '_hash');

    if ($content_hash !== $stored_hash) {
        // Content has been tampered with
        wp_cache_delete($validation_key, 'validated_cache');
        return false;
    }

    return $cached_data;
}

Best Practices

Cache Strategy Guidelines

  1. Layer Your Caches: Use multiple cache layers for optimal performance
  2. Cache Invalidation: Implement proper cache clearing strategies
  3. Monitor Performance: Track cache hit ratios and performance metrics
  4. Regular Maintenance: Clean up expired and stale cache entries
  5. Security First: Implement secure caching practices

Performance Optimization

  1. Cache Static Assets: Leverage browser caching for static content
  2. Database Query Caching: Cache expensive database operations
  3. Object Caching: Use Redis or Memcached for object caching
  4. CDN Integration: Distribute content globally with CDN caching

Monitoring and Maintenance

  1. Cache Size Monitoring: Monitor cache directory sizes
  2. Hit/Miss Ratio Tracking: Track cache effectiveness
  3. Automatic Cleanup: Implement automated cache cleanup
  4. Performance Alerts: Set up alerts for cache issues

Master comprehensive caching strategies for optimal WordPress performance.

On this page