By Devport Team | Last updated: 2025-07-12 | 60 min read

WordPress Performance Optimization: The Complete Developer's Guide

In today's web landscape, performance isn't just a nice-to-have—it's essential for user experience, SEO rankings, and conversion rates. A one-second delay in page load time can result in a 7% reduction in conversions, making WordPress performance optimization critical for any serious website.

This comprehensive guide covers everything from basic optimizations to advanced techniques, helping you transform sluggish WordPress sites into lightning-fast experiences. Whether you're dealing with a small blog or a high-traffic e-commerce site, you'll find actionable strategies to dramatically improve performance.

By the end of this guide, you'll understand how to achieve Core Web Vitals compliance, implement effective caching strategies, optimize databases, and leverage modern performance techniques that put your WordPress site ahead of the competition.

Table of Contents

  1. Understanding WordPress Performance
  2. Core Web Vitals and Metrics
  3. Server and Hosting Optimization
  4. Caching Strategies
  5. Database Optimization
  6. Frontend Performance
  7. Advanced Techniques

Understanding WordPress Performance

The Performance Stack

WordPress performance optimization involves multiple layers, each contributing to overall site speed:

┌─────────────────────────────────────┐
│         User's Browser              │
├─────────────────────────────────────┤
│            CDN Layer                │
├─────────────────────────────────────┤
│         Web Server Cache            │
├─────────────────────────────────────┤
│     PHP Processing (WordPress)      │
├─────────────────────────────────────┤
│        Database (MySQL)             │
├─────────────────────────────────────┤
│         Server Hardware             │
└─────────────────────────────────────┘

Performance Bottlenecks

1. Database Queries

// BAD: Inefficient query in a loop
foreach ($post_ids as $id) {
    $post = get_post($id);
    // Process post
}

// GOOD: Single query with proper caching
$posts = get_posts([
    'post__in' => $post_ids,
    'posts_per_page' => -1,
    'update_post_meta_cache' => false,
    'update_post_term_cache' => false
]);

2. External HTTP Requests

// BAD: Uncached external API call
function get_twitter_followers() {
    $response = wp_remote_get('https://api.twitter.com/...');
    return json_decode(wp_remote_retrieve_body($response));
}

// GOOD: Cached with transients
function get_twitter_followers() {
    $cache_key = 'twitter_followers';
    $followers = get_transient($cache_key);

    if (false === $followers) {
        $response = wp_remote_get('https://api.twitter.com/...');
        $followers = json_decode(wp_remote_retrieve_body($response));
        set_transient($cache_key, $followers, HOUR_IN_SECONDS);
    }

    return $followers;
}

3. Unoptimized Images

<!-- BAD: Large, unoptimized image -->
<img src="hero-image.jpg" alt="Hero">

<!-- GOOD: Responsive, optimized images -->
<picture>
    <source media="(max-width: 768px)" srcset="hero-mobile.webp">
    <source media="(max-width: 1200px)" srcset="hero-tablet.webp">
    <source type="image/webp" srcset="hero-desktop.webp">
    <img src="hero-desktop.jpg" alt="Hero" loading="lazy" decoding="async">
</picture>

Measuring Performance Impact

// Performance profiling helper
class Performance_Monitor {
    private static $timers = [];

    public static function start($name) {
        self::$timers[$name] = [
            'start' => microtime(true),
            'memory_start' => memory_get_usage()
        ];
    }

    public static function stop($name) {
        if (!isset(self::$timers[$name])) {
            return;
        }

        $timer = self::$timers[$name];
        $duration = microtime(true) - $timer['start'];
        $memory = memory_get_usage() - $timer['memory_start'];

        error_log(sprintf(
            '[Performance] %s: %.4f seconds, %.2f MB',
            $name,
            $duration,
            $memory / 1024 / 1024
        ));

        return [
            'duration' => $duration,
            'memory' => $memory
        ];
    }
}

// Usage
Performance_Monitor::start('database_query');
$results = $wpdb->get_results($sql);
Performance_Monitor::stop('database_query');

Core Web Vitals and Metrics

Understanding Core Web Vitals

Google's Core Web Vitals are critical metrics for user experience and SEO:

  1. Largest Contentful Paint (LCP): Loading performance
  2. Target: < 2.5 seconds
  3. Measures when the largest content element becomes visible

  4. First Input Delay (FID): Interactivity

  5. Target: < 100 milliseconds
  6. Measures time from user interaction to browser response

  7. Cumulative Layout Shift (CLS): Visual stability

  8. Target: < 0.1
  9. Measures unexpected layout shifts during page load

Measuring Core Web Vitals

// Real User Monitoring (RUM) for Core Web Vitals
if ('web-vitals' in window) {
    function sendToAnalytics(metric) {
        const body = JSON.stringify({
            name: metric.name,
            value: metric.value,
            delta: metric.delta,
            id: metric.id,
            url: window.location.href,
            timestamp: Date.now()
        });

        // Use sendBeacon for reliability
        if (navigator.sendBeacon) {
            navigator.sendBeacon('/analytics', body);
        }
    }

    webVitals.getCLS(sendToAnalytics);
    webVitals.getFID(sendToAnalytics);
    webVitals.getLCP(sendToAnalytics);
    webVitals.getFCP(sendToAnalytics);
    webVitals.getTTFB(sendToAnalytics);
}

Optimizing for LCP

// Preload critical resources
add_action('wp_head', function() {
    // Preload hero image
    $hero_image = get_field('hero_image');
    if ($hero_image) {
        printf(
            '<link rel="preload" as="image" href="%s" fetchpriority="high">',
            esc_url($hero_image['url'])
        );
    }

    // Preload critical fonts
    $fonts = [
        '/fonts/inter-var.woff2',
        '/fonts/jetbrains-mono.woff2'
    ];

    foreach ($fonts as $font) {
        printf(
            '<link rel="preload" as="font" type="font/woff2" href="%s" crossorigin>',
            esc_url(get_theme_file_uri($font))
        );
    }
});

// Optimize above-the-fold content
add_filter('the_content', function($content) {
    if (!is_singular()) {
        return $content;
    }

    // Add fetchpriority to first image
    $content = preg_replace(
        '/<img(.*?)>/i',
        '<img$1 fetchpriority="high">',
        $content,
        1
    );

    return $content;
}, 20);

Reducing FID

// Break up long tasks
function optimizeLongTask(items) {
    // Instead of processing all items at once
    // items.forEach(item => processItem(item));

    // Process in chunks with idle callback
    let index = 0;

    function processChunk() {
        const chunkSize = 10;
        const chunk = items.slice(index, index + chunkSize);

        chunk.forEach(item => processItem(item));
        index += chunkSize;

        if (index < items.length) {
            requestIdleCallback(processChunk);
        }
    }

    requestIdleCallback(processChunk);
}

// Defer non-critical JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Load non-critical scripts after page load
    const deferredScripts = [
        '/assets/js/analytics.js',
        '/assets/js/social-share.js',
        '/assets/js/comments.js'
    ];

    deferredScripts.forEach(src => {
        const script = document.createElement('script');
        script.src = src;
        script.async = true;
        document.body.appendChild(script);
    });
});

Preventing CLS

/* Reserve space for dynamic content */
.hero-image {
    aspect-ratio: 16/9;
    width: 100%;
    background-color: #f0f0f0;
}

/* Prevent font swap layout shift */
@font-face {
    font-family: 'Inter';
    src: url('/fonts/inter.woff2') format('woff2');
    font-display: optional; /* or swap with size-adjust */
    size-adjust: 100.6%; /* Match fallback font metrics */
}

/* Fixed dimensions for ads */
.ad-container {
    min-height: 250px;
    min-width: 300px;
}

/* Skeleton screens for dynamic content */
.post-skeleton {
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: loading 1.5s infinite;
}

@keyframes loading {
    0% { background-position: 200% 0; }
    100% { background-position: -200% 0; }
}

Server and Hosting Optimization

Choosing the Right Hosting

Hosting Types Comparison

Type Best For Performance Cost Management
Shared Small sites Poor $ Managed
VPS Growing sites Good $$ Semi-managed
Dedicated Large sites Excellent $$$$ Unmanaged
Managed WordPress All sizes Very Good $$$ Fully managed
Cloud (AWS/GCP) Enterprise Excellent $$-$$$$ Unmanaged

Server-Level Optimizations

1. PHP Configuration

; php.ini optimizations
memory_limit = 256M
max_execution_time = 300
max_input_time = 300
max_input_vars = 5000
upload_max_filesize = 50M
post_max_size = 50M

; OPcache settings
opcache.enable = 1
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 10000
opcache.revalidate_freq = 0
opcache.validate_timestamps = 1
opcache.save_comments = 1
opcache.enable_cli = 1

2. MySQL Optimization

-- my.cnf optimizations
[mysqld]
# InnoDB settings
innodb_buffer_pool_size = 1G  # 70-80% of available RAM
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT

# Query cache (MySQL 5.7 and below)
query_cache_type = 1
query_cache_size = 64M
query_cache_limit = 2M

# Connection settings
max_connections = 150
thread_cache_size = 8

# Temporary tables
tmp_table_size = 64M
max_heap_table_size = 64M

# Slow query log
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2

3. Nginx Configuration

# nginx.conf optimization
worker_processes auto;
worker_connections 2048;

http {
    # Enable gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript 
               application/javascript application/xml+rss 
               application/json application/vnd.ms-fontobject 
               application/x-font-ttf font/opentype image/svg+xml;

    # Enable Brotli compression
    brotli on;
    brotli_comp_level 6;
    brotli_types text/plain text/css text/xml text/javascript 
                 application/javascript application/xml+rss 
                 application/json font/woff font/woff2;

    # FastCGI cache
    fastcgi_cache_path /var/cache/nginx levels=1:2 
                       keys_zone=WORDPRESS:100m 
                       inactive=60m max_size=1g;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";

    # Buffer sizes
    client_body_buffer_size 128k;
    client_max_body_size 50m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 16k;

    # Timeouts
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 15;
    send_timeout 10;

    # File cache
    open_file_cache max=2000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}

# WordPress site configuration
server {
    listen 80;
    server_name example.com;
    root /var/www/wordpress;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Cache static files
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|woff|woff2)$ {
        expires 365d;
        add_header Cache-Control "public, immutable";
    }

    # FastCGI cache exceptions
    set $skip_cache 0;

    # POST requests and URLs with query string
    if ($request_method = POST) {
        set $skip_cache 1;
    }
    if ($query_string != "") {
        set $skip_cache 1;
    }

    # Don't cache URIs containing the following segments
    if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|sitemap") {
        set $skip_cache 1;
    }

    # Don't use cache for logged-in users
    if ($http_cookie ~* "wordpress_logged_in") {
        set $skip_cache 1;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;

        # FastCGI cache
        fastcgi_cache WORDPRESS;
        fastcgi_cache_valid 200 60m;
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        add_header X-FastCGI-Cache $upstream_cache_status;
    }
}

HTTP/2 and HTTP/3 Setup

# Enable HTTP/2
server {
    listen 443 ssl http2;
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;

    # HTTP/2 Push
    location / {
        http2_push /css/style.css;
        http2_push /js/main.js;
        http2_push /fonts/inter.woff2;
    }
}

# Enable HTTP/3 (QUIC)
server {
    listen 443 quic reuseport;
    listen 443 ssl http2;

    # Add Alt-Svc header for HTTP/3
    add_header alt-svc 'h3=":443"; ma=86400';
}

Caching Strategies

Multi-Layer Caching Architecture

┌─────────────────────────────────┐
│     Browser Cache (Client)      │ ← 0ms
├─────────────────────────────────┤
│    CDN Cache (Edge Servers)     │ ← 10-50ms
├─────────────────────────────────┤
│   Page Cache (Nginx/Varnish)    │ ← 1-5ms
├─────────────────────────────────┤
│  Object Cache (Redis/Memcached) │ ← 1-2ms
├─────────────────────────────────┤
│   OpCode Cache (OPcache)        │ ← 0.1ms
├─────────────────────────────────┤
│   Database Query Cache          │ ← 1-10ms
└─────────────────────────────────┘

Page Caching Implementation

// Advanced page caching with cache warming
class Advanced_Page_Cache {
    private $cache_dir;
    private $cache_time = 3600; // 1 hour

    public function __construct() {
        $this->cache_dir = WP_CONTENT_DIR . '/cache/pages/';

        add_action('init', [$this, 'serve_cached_page'], 1);
        add_action('save_post', [$this, 'clear_post_cache']);
        add_action('comment_post', [$this, 'clear_post_cache']);
        add_action('wp_ajax_warm_cache', [$this, 'warm_cache']);
        add_action('wp_ajax_nopriv_warm_cache', [$this, 'warm_cache']);
    }

    public function serve_cached_page() {
        if (!$this->should_cache()) {
            return;
        }

        $cache_file = $this->get_cache_file();

        if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $this->cache_time) {
            // Serve cached content
            readfile($cache_file);
            echo "\n<!-- Served from page cache: " . date('Y-m-d H:i:s', filemtime($cache_file)) . " -->";
            exit;
        }

        // Start output buffering for cache generation
        ob_start([$this, 'save_cache']);
    }

    private function should_cache() {
        // Don't cache for logged-in users
        if (is_user_logged_in()) {
            return false;
        }

        // Don't cache POST requests
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            return false;
        }

        // Don't cache URLs with query strings (except specific ones)
        $allowed_params = ['utm_source', 'utm_medium', 'utm_campaign'];
        $query_string = $_SERVER['QUERY_STRING'];

        if (!empty($query_string)) {
            parse_str($query_string, $params);
            $extra_params = array_diff(array_keys($params), $allowed_params);
            if (!empty($extra_params)) {
                return false;
            }
        }

        // Don't cache specific pages
        $no_cache_urls = ['/wp-admin/', '/wp-login.php', '/cart/', '/checkout/'];
        $request_uri = $_SERVER['REQUEST_URI'];

        foreach ($no_cache_urls as $url) {
            if (strpos($request_uri, $url) !== false) {
                return false;
            }
        }

        return true;
    }

    private function get_cache_file() {
        $url = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $hash = md5($url);
        $dir = $this->cache_dir . substr($hash, 0, 2) . '/';

        if (!file_exists($dir)) {
            wp_mkdir_p($dir);
        }

        return $dir . $hash . '.html';
    }

    public function save_cache($content) {
        if (!$this->should_cache()) {
            return $content;
        }

        $cache_file = $this->get_cache_file();

        // Minify HTML before caching
        $content = $this->minify_html($content);

        file_put_contents($cache_file, $content);

        return $content;
    }

    private function minify_html($content) {
        // Remove HTML comments (keep IE conditionals)
        $content = preg_replace('/<!--(?!\[if).*?-->/s', '', $content);

        // Remove whitespace between tags
        $content = preg_replace('/>\s+</', '><', $content);

        // Remove trailing whitespace
        $content = preg_replace('/\s+$/', '', $content);

        return $content;
    }

    public function clear_post_cache($post_id) {
        // Clear specific post cache
        $post = get_post($post_id);
        if (!$post) {
            return;
        }

        $urls = [
            get_permalink($post_id),
            home_url('/'),
            get_post_type_archive_link($post->post_type)
        ];

        // Add category and tag pages
        $categories = get_the_category($post_id);
        foreach ($categories as $category) {
            $urls[] = get_category_link($category);
        }

        $tags = get_the_tags($post_id);
        if ($tags) {
            foreach ($tags as $tag) {
                $urls[] = get_tag_link($tag);
            }
        }

        // Clear cache for each URL
        foreach ($urls as $url) {
            $this->clear_url_cache($url);
        }
    }

    private function clear_url_cache($url) {
        $parsed = parse_url($url);
        $cache_url = $parsed['host'] . $parsed['path'];
        $hash = md5($cache_url);
        $dir = $this->cache_dir . substr($hash, 0, 2) . '/';
        $file = $dir . $hash . '.html';

        if (file_exists($file)) {
            unlink($file);
        }
    }

    public function warm_cache() {
        // Get URLs to warm
        $urls = $this->get_urls_to_warm();

        foreach ($urls as $url) {
            wp_remote_get($url, [
                'blocking' => false,
                'timeout' => 0.01,
                'headers' => [
                    'X-Cache-Warmer' => 'true'
                ]
            ]);
        }

        wp_die('Cache warmed successfully');
    }

    private function get_urls_to_warm() {
        $urls = [home_url('/')];

        // Recent posts
        $posts = get_posts([
            'posts_per_page' => 20,
            'post_status' => 'publish'
        ]);

        foreach ($posts as $post) {
            $urls[] = get_permalink($post);
        }

        // Important pages
        $pages = get_pages([
            'meta_key' => '_warm_cache',
            'meta_value' => 'yes'
        ]);

        foreach ($pages as $page) {
            $urls[] = get_permalink($page);
        }

        return $urls;
    }
}

// Initialize
new Advanced_Page_Cache();

Object Caching with Redis

// Redis object cache implementation
class Redis_Object_Cache {
    private $redis;
    private $is_connected = false;
    private $key_prefix;

    public function __construct() {
        $this->key_prefix = wp_hash(home_url()) . ':';
        $this->connect();

        // Replace WordPress object cache
        if ($this->is_connected) {
            wp_cache_add_global_groups(['users', 'userlogins', 'usermeta', 'site-options', 'site-transient']);
            wp_cache_add_non_persistent_groups(['counts', 'plugins']);
        }
    }

    private function connect() {
        try {
            $this->redis = new Redis();
            $this->redis->connect('127.0.0.1', 6379);

            // Authentication if needed
            if (defined('REDIS_PASSWORD')) {
                $this->redis->auth(REDIS_PASSWORD);
            }

            // Select database
            if (defined('REDIS_DATABASE')) {
                $this->redis->select(REDIS_DATABASE);
            }

            $this->is_connected = true;
        } catch (Exception $e) {
            error_log('Redis connection failed: ' . $e->getMessage());
            $this->is_connected = false;
        }
    }

    public function get($key, $group = 'default') {
        if (!$this->is_connected) {
            return false;
        }

        $redis_key = $this->build_key($key, $group);

        try {
            $value = $this->redis->get($redis_key);
            if ($value === false) {
                return false;
            }

            return maybe_unserialize($value);
        } catch (Exception $e) {
            return false;
        }
    }

    public function set($key, $value, $group = 'default', $expire = 0) {
        if (!$this->is_connected) {
            return false;
        }

        $redis_key = $this->build_key($key, $group);
        $value = maybe_serialize($value);

        try {
            if ($expire > 0) {
                return $this->redis->setex($redis_key, $expire, $value);
            } else {
                return $this->redis->set($redis_key, $value);
            }
        } catch (Exception $e) {
            return false;
        }
    }

    public function delete($key, $group = 'default') {
        if (!$this->is_connected) {
            return false;
        }

        $redis_key = $this->build_key($key, $group);

        try {
            return $this->redis->del($redis_key) > 0;
        } catch (Exception $e) {
            return false;
        }
    }

    public function flush() {
        if (!$this->is_connected) {
            return false;
        }

        try {
            // Flush only keys with our prefix
            $pattern = $this->key_prefix . '*';
            $keys = $this->redis->keys($pattern);

            if (!empty($keys)) {
                return $this->redis->del($keys) > 0;
            }

            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    private function build_key($key, $group) {
        return $this->key_prefix . $group . ':' . $key;
    }

    public function stats() {
        if (!$this->is_connected) {
            return false;
        }

        try {
            $info = $this->redis->info();

            return [
                'hits' => $info['keyspace_hits'] ?? 0,
                'misses' => $info['keyspace_misses'] ?? 0,
                'memory' => $info['used_memory_human'] ?? '0B',
                'uptime' => $info['uptime_in_seconds'] ?? 0
            ];
        } catch (Exception $e) {
            return false;
        }
    }
}

// Initialize Redis cache
if (defined('ENABLE_REDIS_CACHE') && ENABLE_REDIS_CACHE) {
    $GLOBALS['wp_object_cache'] = new Redis_Object_Cache();
}

Fragment Caching

// Fragment caching for expensive operations
function fragment_cache($key, $ttl, $callback, $group = 'fragments') {
    $cache_key = 'fragment_' . md5($key);
    $cached = wp_cache_get($cache_key, $group);

    if ($cached !== false) {
        return $cached;
    }

    // Execute callback and cache result
    $result = call_user_func($callback);
    wp_cache_set($cache_key, $result, $group, $ttl);

    return $result;
}

// Usage example
$popular_posts = fragment_cache('popular_posts_sidebar', 3600, function() {
    return new WP_Query([
        'posts_per_page' => 5,
        'meta_key' => 'post_views_count',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
        'date_query' => [
            [
                'after' => '1 week ago'
            ]
        ]
    ]);
});

Database Optimization

Query Optimization

// Optimize common queries
class Database_Optimizer {

    public function __construct() {
        add_filter('posts_request', [$this, 'optimize_main_query'], 10, 2);
        add_filter('pre_get_posts', [$this, 'optimize_queries']);
        add_action('init', [$this, 'add_custom_indexes']);
    }

    public function optimize_main_query($query, $wp_query) {
        // Skip if in admin or not main query
        if (is_admin() || !$wp_query->is_main_query()) {
            return $query;
        }

        // Add SQL_CALC_FOUND_ROWS only when needed
        if (!$wp_query->get('no_found_rows')) {
            $query = str_replace('SQL_CALC_FOUND_ROWS', '', $query);
        }

        // Add index hints for better performance
        if ($wp_query->is_search()) {
            $query = str_replace('FROM wp_posts', 'FROM wp_posts USE INDEX (type_status_date)', $query);
        }

        return $query;
    }

    public function optimize_queries($query) {
        // Disable term and meta caching for queries that don't need it
        if (!is_admin() && $query->is_main_query()) {
            if ($query->is_home() || $query->is_archive()) {
                $query->set('update_post_term_cache', false);
                $query->set('update_post_meta_cache', false);
            }
        }

        // Limit fields for archive pages
        if ($query->is_archive() || $query->is_search()) {
            $query->set('fields', 'ids');
        }

        return $query;
    }

    public function add_custom_indexes() {
        global $wpdb;

        // Check if indexes exist before adding
        $indexes = [
            'postmeta_meta_key_value' => "ALTER TABLE {$wpdb->postmeta} ADD INDEX meta_key_value (meta_key(191), meta_value(50))",
            'posts_post_type_status_date' => "ALTER TABLE {$wpdb->posts} ADD INDEX type_status_date (post_type, post_status, post_date)",
            'comments_comment_approved_date' => "ALTER TABLE {$wpdb->comments} ADD INDEX comment_approved_date (comment_approved, comment_date_gmt)"
        ];

        foreach ($indexes as $name => $sql) {
            $existing = $wpdb->get_results("SHOW INDEX FROM {$wpdb->posts} WHERE Key_name = '{$name}'");

            if (empty($existing)) {
                $wpdb->query($sql);
            }
        }
    }
}

new Database_Optimizer();

Database Cleanup

// Automated database cleanup
class Database_Cleanup {

    public function __construct() {
        // Schedule cleanup
        if (!wp_next_scheduled('database_cleanup_cron')) {
            wp_schedule_event(time(), 'weekly', 'database_cleanup_cron');
        }

        add_action('database_cleanup_cron', [$this, 'run_cleanup']);
    }

    public function run_cleanup() {
        global $wpdb;

        // Clean up post revisions (keep last 5)
        $wpdb->query("
            DELETE r1 FROM {$wpdb->posts} r1
            INNER JOIN (
                SELECT post_parent, MAX(post_modified) as latest_date
                FROM {$wpdb->posts}
                WHERE post_type = 'revision'
                GROUP BY post_parent
                HAVING COUNT(*) > 5
            ) r2
            ON r1.post_parent = r2.post_parent
            WHERE r1.post_type = 'revision'
            AND r1.post_modified < r2.latest_date
            AND r1.post_modified < DATE_SUB(r2.latest_date, INTERVAL 30 DAY)
        ");

        // Clean up orphaned postmeta
        $wpdb->query("
            DELETE pm FROM {$wpdb->postmeta} pm
            LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
            WHERE p.ID IS NULL
        ");

        // Clean up expired transients
        $wpdb->query("
            DELETE FROM {$wpdb->options}
            WHERE option_name LIKE '%_transient_timeout_%'
            AND option_value < UNIX_TIMESTAMP()
        ");

        $wpdb->query("
            DELETE FROM {$wpdb->options}
            WHERE option_name LIKE '%_transient_%'
            AND option_name NOT LIKE '%_transient_timeout_%'
            AND option_name NOT IN (
                SELECT CONCAT('_transient_', SUBSTRING(option_name, 19))
                FROM (SELECT option_name FROM {$wpdb->options}) AS temp
                WHERE option_name LIKE '%_transient_timeout_%'
            )
        ");

        // Clean up spam and trash comments
        $wpdb->query("
            DELETE FROM {$wpdb->comments}
            WHERE comment_approved = 'spam'
            AND comment_date < DATE_SUB(NOW(), INTERVAL 30 DAY)
        ");

        // Optimize tables
        $tables = $wpdb->get_col("SHOW TABLES LIKE '{$wpdb->prefix}%'");
        foreach ($tables as $table) {
            $wpdb->query("OPTIMIZE TABLE {$table}");
        }

        // Log cleanup results
        $this->log_cleanup_stats();
    }

    private function log_cleanup_stats() {
        global $wpdb;

        $stats = [
            'total_posts' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts}"),
            'total_revisions' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'revision'"),
            'total_postmeta' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->postmeta}"),
            'total_options' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->options}"),
            'database_size' => $wpdb->get_var("
                SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2)
                FROM information_schema.TABLES
                WHERE table_schema = DATABASE()
            ")
        ];

        update_option('database_cleanup_stats', $stats);

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Database cleanup completed: ' . json_encode($stats));
        }
    }
}

new Database_Cleanup();

Query Monitoring

// Monitor and log slow queries
class Query_Monitor {
    private $queries = [];
    private $threshold = 0.05; // 50ms

    public function __construct() {
        if (!defined('SAVEQUERIES')) {
            define('SAVEQUERIES', true);
        }

        add_action('shutdown', [$this, 'analyze_queries']);
    }

    public function analyze_queries() {
        if (!defined('SAVEQUERIES') || !SAVEQUERIES) {
            return;
        }

        global $wpdb;

        foreach ($wpdb->queries as $query) {
            list($sql, $duration, $caller) = $query;

            if ($duration > $this->threshold) {
                $this->queries[] = [
                    'sql' => $sql,
                    'duration' => $duration,
                    'caller' => $caller
                ];
            }
        }

        if (!empty($this->queries)) {
            $this->log_slow_queries();
        }

        // Add query stats to footer in development
        if (WP_DEBUG && !is_admin()) {
            add_action('wp_footer', [$this, 'display_stats'], 999);
        }
    }

    private function log_slow_queries() {
        $log_file = WP_CONTENT_DIR . '/slow-queries.log';

        foreach ($this->queries as $query) {
            $log_entry = sprintf(
                "[%s] Duration: %.4fs | Caller: %s | SQL: %s\n",
                date('Y-m-d H:i:s'),
                $query['duration'],
                $query['caller'],
                $query['sql']
            );

            error_log($log_entry, 3, $log_file);
        }
    }

    public function display_stats() {
        global $wpdb;

        $total_queries = count($wpdb->queries);
        $total_time = 0;

        foreach ($wpdb->queries as $query) {
            $total_time += $query[1];
        }

        echo "\n<!-- Query Stats: {$total_queries} queries in {$total_time}s -->\n";

        if (!empty($this->queries)) {
            echo "<!-- Slow Queries:\n";
            foreach ($this->queries as $query) {
                printf("  %.4fs: %s\n", $query['duration'], substr($query['sql'], 0, 100));
            }
            echo "-->\n";
        }
    }
}

new Query_Monitor();

Frontend Performance

Critical CSS Generation

// Generate and inline critical CSS
class Critical_CSS {
    private $critical_css = '';

    public function __construct() {
        add_action('wp_head', [$this, 'inline_critical_css'], 1);
        add_filter('style_loader_tag', [$this, 'async_load_css'], 10, 4);
    }

    public function generate_critical_css() {
        // Critical CSS for above-the-fold content
        $critical_css = '
            /* Reset and base styles */
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: #333; }

            /* Header styles */
            .header { background: #fff; padding: 1rem 0; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
            .header-container { max-width: 1200px; margin: 0 auto; padding: 0 1rem; }
            .logo { font-size: 1.5rem; font-weight: bold; text-decoration: none; color: #333; }

            /* Hero section */
            .hero { padding: 4rem 0; background: #f8f9fa; }
            .hero h1 { font-size: 2.5rem; margin-bottom: 1rem; }
            .hero p { font-size: 1.25rem; color: #666; }

            /* Content layout */
            .container { max-width: 1200px; margin: 0 auto; padding: 0 1rem; }
            .content { padding: 3rem 0; }

            /* Utilities */
            .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0; }
        ';

        // Minify CSS
        $critical_css = preg_replace('/\s+/', ' ', $critical_css);
        $critical_css = preg_replace('/\/\*.*?\*\//', '', $critical_css);
        $critical_css = str_replace(': ', ':', $critical_css);
        $critical_css = str_replace('; ', ';', $critical_css);
        $critical_css = str_replace(' {', '{', $critical_css);
        $critical_css = str_replace('{ ', '{', $critical_css);
        $critical_css = str_replace(' }', '}', $critical_css);
        $critical_css = str_replace('} ', '}', $critical_css);

        return $critical_css;
    }

    public function inline_critical_css() {
        $critical_css = get_transient('critical_css');

        if (!$critical_css) {
            $critical_css = $this->generate_critical_css();
            set_transient('critical_css', $critical_css, WEEK_IN_SECONDS);
        }

        echo '<style id="critical-css">' . $critical_css . '</style>';

        // Add preload for main stylesheet
        echo '<link rel="preload" href="' . get_stylesheet_uri() . '" as="style">';
    }

    public function async_load_css($html, $handle, $href, $media) {
        // Skip critical styles
        if (in_array($handle, ['critical-css', 'admin-bar'])) {
            return $html;
        }

        // Convert to async loading
        $html = '<link rel="preload" href="' . $href . '" as="style" onload="this.onload=null;this.rel=\'stylesheet\'">';
        $html .= '<noscript><link rel="stylesheet" href="' . $href . '"></noscript>';

        return $html;
    }
}

new Critical_CSS();

JavaScript Optimization

// Advanced JavaScript optimization
class JavaScript_Optimizer {
    private $scripts_to_defer = [];
    private $scripts_to_async = [];
    private $inline_scripts = [];

    public function __construct() {
        add_action('wp_enqueue_scripts', [$this, 'optimize_scripts'], 999);
        add_filter('script_loader_tag', [$this, 'add_async_defer'], 10, 3);
        add_action('wp_footer', [$this, 'inline_critical_js'], 5);
    }

    public function optimize_scripts() {
        // Define script loading strategy
        $this->scripts_to_defer = [
            'comment-reply',
            'wp-embed',
            'jquery-migrate'
        ];

        $this->scripts_to_async = [
            'google-analytics',
            'facebook-pixel'
        ];

        // Remove jQuery for modern browsers
        if (!is_admin() && !is_user_logged_in()) {
            wp_deregister_script('jquery');
            wp_register_script('jquery', false, [], false, false);
        }

        // Combine and minify scripts
        $this->combine_scripts();
    }

    public function add_async_defer($tag, $handle, $src) {
        // Add defer attribute
        if (in_array($handle, $this->scripts_to_defer)) {
            return str_replace(' src', ' defer src', $tag);
        }

        // Add async attribute
        if (in_array($handle, $this->scripts_to_async)) {
            return str_replace(' src', ' async src', $tag);
        }

        // Add module type for ES6 modules
        if (strpos($src, '.mjs') !== false) {
            return str_replace('<script', '<script type="module"', $tag);
        }

        return $tag;
    }

    private function combine_scripts() {
        global $wp_scripts;

        $combined_scripts = [];
        $handles_to_combine = ['theme-functions', 'theme-navigation', 'theme-skip-link'];

        foreach ($handles_to_combine as $handle) {
            if (isset($wp_scripts->registered[$handle])) {
                $script = $wp_scripts->registered[$handle];
                $combined_scripts[] = file_get_contents($script->src);
                wp_dequeue_script($handle);
            }
        }

        if (!empty($combined_scripts)) {
            $combined_content = implode(";\n", $combined_scripts);
            $hash = md5($combined_content);
            $filename = "combined-{$hash}.js";
            $filepath = WP_CONTENT_DIR . "/cache/js/{$filename}";

            if (!file_exists($filepath)) {
                wp_mkdir_p(dirname($filepath));

                // Minify if possible
                if (class_exists('JShrink\Minifier')) {
                    $combined_content = \JShrink\Minifier::minify($combined_content);
                }

                file_put_contents($filepath, $combined_content);
            }

            wp_enqueue_script(
                'theme-combined',
                content_url("cache/js/{$filename}"),
                [],
                null,
                true
            );
        }
    }

    public function inline_critical_js() {
        // Inline critical JavaScript
        ?>
        <script>
        // Feature detection and polyfills
        (function() {
            // Check for IntersectionObserver
            if (!('IntersectionObserver' in window)) {
                var script = document.createElement('script');
                script.src = '<?php echo get_template_directory_uri(); ?>/js/intersection-observer.js';
                document.head.appendChild(script);
            }

            // Lazy load images
            if ('loading' in HTMLImageElement.prototype) {
                var images = document.querySelectorAll('img[loading="lazy"]');
                images.forEach(function(img) {
                    img.src = img.dataset.src || img.src;
                });
            } else {
                var script = document.createElement('script');
                script.src = '<?php echo get_template_directory_uri(); ?>/js/lazy-load.js';
                document.body.appendChild(script);
            }

            // Prefetch links on hover
            var prefetched = new Set();
            document.addEventListener('mouseover', function(e) {
                var link = e.target.closest('a');
                if (link && link.href && !prefetched.has(link.href)) {
                    var url = new URL(link.href);
                    if (url.origin === location.origin) {
                        var prefetch = document.createElement('link');
                        prefetch.rel = 'prefetch';
                        prefetch.href = link.href;
                        document.head.appendChild(prefetch);
                        prefetched.add(link.href);
                    }
                }
            });
        })();
        </script>
        <?php
    }
}

new JavaScript_Optimizer();

Image Optimization

// Advanced image optimization
class Image_Optimizer {
    private $sizes = [
        'thumbnail' => [150, 150, true],
        'medium' => [300, 300, false],
        'medium_large' => [768, 0, false],
        'large' => [1024, 1024, false],
        'hero' => [1920, 1080, true],
        'card' => [400, 300, true]
    ];

    public function __construct() {
        add_action('init', [$this, 'register_image_sizes']);
        add_filter('wp_generate_attachment_metadata', [$this, 'optimize_uploads'], 10, 2);
        add_filter('the_content', [$this, 'lazy_load_content_images']);
        add_filter('wp_get_attachment_image_attributes', [$this, 'add_lazy_loading'], 10, 3);
        add_action('wp_head', [$this, 'preload_hero_image']);
    }

    public function register_image_sizes() {
        foreach ($this->sizes as $name => $size) {
            add_image_size($name, $size[0], $size[1], $size[2]);
        }

        // Add WebP support
        add_filter('wp_generate_attachment_metadata', [$this, 'generate_webp_images'], 15, 2);
    }

    public function optimize_uploads($metadata, $attachment_id) {
        $file = get_attached_file($attachment_id);

        if (!$file || !file_exists($file)) {
            return $metadata;
        }

        // Optimize with ImageMagick if available
        if (extension_loaded('imagick')) {
            $imagick = new Imagick($file);

            // Strip metadata
            $imagick->stripImage();

            // Optimize based on format
            $format = $imagick->getImageFormat();

            switch ($format) {
                case 'JPEG':
                    $imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
                    $imagick->setImageCompressionQuality(85);
                    $imagick->setSamplingFactors(['2x2', '1x1', '1x1']);
                    $imagick->setInterlaceScheme(Imagick::INTERLACE_PLANE);
                    break;

                case 'PNG':
                    $imagick->setImageCompression(Imagick::COMPRESSION_ZIP);
                    $imagick->setOption('png:compression-level', '9');
                    break;
            }

            $imagick->writeImage($file);
            $imagick->destroy();
        }

        return $metadata;
    }

    public function generate_webp_images($metadata, $attachment_id) {
        if (!function_exists('imagewebp')) {
            return $metadata;
        }

        $file = get_attached_file($attachment_id);
        $info = pathinfo($file);

        // Skip if already WebP
        if ($info['extension'] === 'webp') {
            return $metadata;
        }

        // Convert main image
        $this->create_webp($file);

        // Convert all sizes
        if (isset($metadata['sizes'])) {
            foreach ($metadata['sizes'] as $size => $data) {
                $size_file = str_replace(basename($file), $data['file'], $file);
                $this->create_webp($size_file);
            }
        }

        return $metadata;
    }

    private function create_webp($file) {
        $info = pathinfo($file);
        $webp_file = $info['dirname'] . '/' . $info['filename'] . '.webp';

        // Skip if WebP already exists
        if (file_exists($webp_file)) {
            return;
        }

        $image = null;

        switch ($info['extension']) {
            case 'jpg':
            case 'jpeg':
                $image = imagecreatefromjpeg($file);
                break;
            case 'png':
                $image = imagecreatefrompng($file);
                break;
        }

        if ($image) {
            imagewebp($image, $webp_file, 85);
            imagedestroy($image);
        }
    }

    public function lazy_load_content_images($content) {
        if (is_feed() || is_admin()) {
            return $content;
        }

        // Add loading="lazy" to images
        $content = preg_replace_callback(
            '/<img([^>]+)>/i',
            function($matches) {
                $img = $matches[0];

                // Skip if already has loading attribute
                if (strpos($img, 'loading=') !== false) {
                    return $img;
                }

                // Add loading="lazy"
                return str_replace('<img', '<img loading="lazy" decoding="async"', $img);
            },
            $content
        );

        return $content;
    }

    public function add_lazy_loading($attributes, $attachment, $size) {
        // Skip for specific images
        if (isset($attributes['class']) && strpos($attributes['class'], 'skip-lazy') !== false) {
            return $attributes;
        }

        $attributes['loading'] = 'lazy';
        $attributes['decoding'] = 'async';

        // Add responsive srcset
        $srcset = wp_get_attachment_image_srcset($attachment->ID, $size);
        if ($srcset) {
            $attributes['srcset'] = $srcset;
            $attributes['sizes'] = wp_get_attachment_image_sizes($attachment->ID, $size);
        }

        return $attributes;
    }

    public function preload_hero_image() {
        if (!is_front_page()) {
            return;
        }

        $hero_image_id = get_theme_mod('hero_image');
        if (!$hero_image_id) {
            return;
        }

        $image_url = wp_get_attachment_image_url($hero_image_id, 'hero');
        $image_srcset = wp_get_attachment_image_srcset($hero_image_id, 'hero');

        if ($image_url) {
            echo '<link rel="preload" as="image" href="' . esc_url($image_url) . '"';
            if ($image_srcset) {
                echo ' imagesrcset="' . esc_attr($image_srcset) . '"';
            }
            echo ' fetchpriority="high">' . "\n";
        }
    }
}

new Image_Optimizer();

Advanced Techniques

Edge Side Includes (ESI)

// ESI implementation for dynamic content caching
class ESI_Handler {
    private $esi_tags = [];

    public function __construct() {
        add_filter('the_content', [$this, 'process_esi_tags']);
        add_action('init', [$this, 'register_esi_endpoints']);
    }

    public function add_esi_tag($name, $callback, $ttl = 300) {
        $this->esi_tags[$name] = [
            'callback' => $callback,
            'ttl' => $ttl
        ];
    }

    public function process_esi_tags($content) {
        // Look for ESI placeholders
        $content = preg_replace_callback(
            '/<!--esi\s+name="([^"]+)"(?:\s+params="([^"]+)")?\s*-->/i',
            [$this, 'replace_esi_tag'],
            $content
        );

        return $content;
    }

    private function replace_esi_tag($matches) {
        $name = $matches[1];
        $params = isset($matches[2]) ? $matches[2] : '';

        // If Varnish/CDN supports ESI
        if ($this->supports_esi()) {
            $url = home_url("/esi/{$name}");
            if ($params) {
                $url .= '?' . $params;
            }

            return '<esi:include src="' . esc_url($url) . '" />';
        }

        // Fallback: render directly
        if (isset($this->esi_tags[$name])) {
            parse_str($params, $parsed_params);
            return call_user_func($this->esi_tags[$name]['callback'], $parsed_params);
        }

        return '';
    }

    private function supports_esi() {
        // Check if behind Varnish or CDN that supports ESI
        return isset($_SERVER['HTTP_X_VARNISH']) || 
               (defined('ESI_ENABLED') && ESI_ENABLED);
    }

    public function register_esi_endpoints() {
        add_rewrite_rule('^esi/([^/]+)/?', 'index.php?esi_endpoint=$matches[1]', 'top');
        add_filter('query_vars', function($vars) {
            $vars[] = 'esi_endpoint';
            return $vars;
        });

        add_action('template_redirect', [$this, 'handle_esi_request']);
    }

    public function handle_esi_request() {
        $endpoint = get_query_var('esi_endpoint');

        if (!$endpoint || !isset($this->esi_tags[$endpoint])) {
            return;
        }

        $tag = $this->esi_tags[$endpoint];
        $output = call_user_func($tag['callback'], $_GET);

        // Set cache headers
        header('Cache-Control: public, max-age=' . $tag['ttl']);
        header('X-ESI-Fragment: ' . $endpoint);

        echo $output;
        exit;
    }
}

// Initialize and register ESI tags
$esi = new ESI_Handler();

// Register dynamic sidebar
$esi->add_esi_tag('popular_posts', function($params) {
    $count = isset($params['count']) ? (int)$params['count'] : 5;

    $posts = get_posts([
        'posts_per_page' => $count,
        'meta_key' => 'post_views_count',
        'orderby' => 'meta_value_num',
        'order' => 'DESC'
    ]);

    ob_start();
    echo '<div class="popular-posts">';
    foreach ($posts as $post) {
        echo '<div class="popular-post">';
        echo '<a href="' . get_permalink($post) . '">' . esc_html($post->post_title) . '</a>';
        echo '</div>';
    }
    echo '</div>';

    return ob_get_clean();
}, 3600); // Cache for 1 hour

Progressive Web App (PWA) Implementation

// Service Worker for offline performance
// sw.js
const CACHE_NAME = 'wp-pwa-v1';
const urlsToCache = [
    '/',
    '/offline',
    '/wp-content/themes/mytheme/style.css',
    '/wp-content/themes/mytheme/js/main.js'
];

// Install event
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => cache.addAll(urlsToCache))
    );
});

// Fetch event with cache strategies
self.addEventListener('fetch', event => {
    const { request } = event;
    const url = new URL(request.url);

    // Cache first for assets
    if (request.destination === 'style' || 
        request.destination === 'script' ||
        request.destination === 'image') {
        event.respondWith(cacheFirst(request));
        return;
    }

    // Network first for HTML
    if (request.mode === 'navigate') {
        event.respondWith(networkFirst(request));
        return;
    }

    // Stale while revalidate for API
    if (url.pathname.startsWith('/wp-json/')) {
        event.respondWith(staleWhileRevalidate(request));
        return;
    }
});

async function cacheFirst(request) {
    const cached = await caches.match(request);
    return cached || fetch(request);
}

async function networkFirst(request) {
    try {
        const response = await fetch(request);
        const cache = await caches.open(CACHE_NAME);
        cache.put(request, response.clone());
        return response;
    } catch (error) {
        const cached = await caches.match(request);
        return cached || caches.match('/offline');
    }
}

async function staleWhileRevalidate(request) {
    const cached = await caches.match(request);

    const fetchPromise = fetch(request).then(response => {
        const cache = caches.open(CACHE_NAME);
        cache.then(cache => cache.put(request, response.clone()));
        return response;
    });

    return cached || fetchPromise;
}
// PHP handler for PWA
class PWA_Handler {

    public function __construct() {
        add_action('wp_enqueue_scripts', [$this, 'register_service_worker']);
        add_action('wp_head', [$this, 'add_pwa_meta']);
        add_filter('query_vars', [$this, 'add_query_vars']);
        add_action('init', [$this, 'add_rewrite_rules']);
        add_action('template_redirect', [$this, 'serve_manifest']);
    }

    public function register_service_worker() {
        if (!is_ssl()) {
            return;
        }

        wp_enqueue_script(
            'service-worker-register',
            get_template_directory_uri() . '/js/sw-register.js',
            [],
            null,
            true
        );

        wp_localize_script('service-worker-register', 'serviceWorkerData', [
            'url' => home_url('/sw.js'),
            'scope' => '/'
        ]);
    }

    public function add_pwa_meta() {
        ?>
        <link rel="manifest" href="<?php echo home_url('/manifest.json'); ?>">
        <meta name="theme-color" content="#2271b1">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="default">
        <meta name="apple-mobile-web-app-title" content="<?php bloginfo('name'); ?>">
        <link rel="apple-touch-icon" href="<?php echo get_template_directory_uri(); ?>/icons/icon-192.png">
        <?php
    }

    public function add_query_vars($vars) {
        $vars[] = 'pwa_route';
        return $vars;
    }

    public function add_rewrite_rules() {
        add_rewrite_rule('^sw\.js$', 'index.php?pwa_route=sw', 'top');
        add_rewrite_rule('^manifest\.json$', 'index.php?pwa_route=manifest', 'top');
    }

    public function serve_manifest() {
        $route = get_query_var('pwa_route');

        if (!$route) {
            return;
        }

        switch ($route) {
            case 'manifest':
                header('Content-Type: application/manifest+json');
                echo json_encode([
                    'name' => get_bloginfo('name'),
                    'short_name' => get_bloginfo('name'),
                    'description' => get_bloginfo('description'),
                    'start_url' => '/',
                    'display' => 'standalone',
                    'theme_color' => '#2271b1',
                    'background_color' => '#ffffff',
                    'icons' => [
                        [
                            'src' => get_template_directory_uri() . '/icons/icon-192.png',
                            'sizes' => '192x192',
                            'type' => 'image/png'
                        ],
                        [
                            'src' => get_template_directory_uri() . '/icons/icon-512.png',
                            'sizes' => '512x512',
                            'type' => 'image/png'
                        ]
                    ]
                ]);
                exit;

            case 'sw':
                header('Content-Type: application/javascript');
                header('Service-Worker-Allowed: /');
                readfile(get_template_directory() . '/js/sw.js');
                exit;
        }
    }
}

new PWA_Handler();

Performance Testing and Monitoring

Automated Performance Testing

// Performance testing suite
class Performance_Tester {
    private $metrics = [];

    public function run_tests() {
        $this->test_page_load_time();
        $this->test_database_queries();
        $this->test_memory_usage();
        $this->test_cache_hit_rate();
        $this->test_core_web_vitals();

        return $this->generate_report();
    }

    private function test_page_load_time() {
        $urls = [
            'homepage' => home_url('/'),
            'blog' => home_url('/blog/'),
            'single_post' => get_permalink(get_posts(['numberposts' => 1])[0]),
            'category' => get_category_link(get_categories(['number' => 1])[0]->term_id)
        ];

        foreach ($urls as $name => $url) {
            $start = microtime(true);
            $response = wp_remote_get($url);
            $duration = microtime(true) - $start;

            $this->metrics['page_load'][$name] = [
                'duration' => $duration,
                'size' => strlen(wp_remote_retrieve_body($response)),
                'status' => wp_remote_retrieve_response_code($response)
            ];
        }
    }

    private function test_database_queries() {
        global $wpdb;

        // Enable query logging
        $wpdb->queries = [];
        define('SAVEQUERIES', true);

        // Run typical queries
        get_posts(['posts_per_page' => 10]);
        get_categories();
        get_tags();

        $this->metrics['database'] = [
            'total_queries' => count($wpdb->queries),
            'total_time' => array_sum(array_column($wpdb->queries, 1)),
            'slow_queries' => array_filter($wpdb->queries, function($query) {
                return $query[1] > 0.05; // Queries over 50ms
            })
        ];
    }

    private function test_memory_usage() {
        $this->metrics['memory'] = [
            'current' => memory_get_usage(true),
            'peak' => memory_get_peak_usage(true),
            'limit' => ini_get('memory_limit')
        ];
    }

    private function test_cache_hit_rate() {
        // Test object cache
        $test_key = 'performance_test_' . time();

        // Set cache
        wp_cache_set($test_key, 'test_value', '', 300);

        // Get from cache
        $start = microtime(true);
        $cached = wp_cache_get($test_key);
        $cache_time = microtime(true) - $start;

        // Get cache stats if available
        $cache_info = [];
        if (function_exists('wp_cache_get_info')) {
            $cache_info = wp_cache_get_info();
        }

        $this->metrics['cache'] = [
            'hit_time' => $cache_time,
            'info' => $cache_info
        ];
    }

    private function test_core_web_vitals() {
        // This would typically integrate with real user monitoring
        // or use Chrome UX Report API
        $this->metrics['core_web_vitals'] = [
            'lcp' => ['value' => 2.3, 'rating' => 'good'],
            'fid' => ['value' => 85, 'rating' => 'good'],
            'cls' => ['value' => 0.08, 'rating' => 'good']
        ];
    }

    private function generate_report() {
        $report = [
            'timestamp' => current_time('mysql'),
            'metrics' => $this->metrics,
            'recommendations' => $this->get_recommendations()
        ];

        // Store report
        update_option('performance_test_latest', $report);

        // Add to history
        $history = get_option('performance_test_history', []);
        $history[] = $report;

        // Keep last 30 reports
        if (count($history) > 30) {
            array_shift($history);
        }

        update_option('performance_test_history', $history);

        return $report;
    }

    private function get_recommendations() {
        $recommendations = [];

        // Page load recommendations
        foreach ($this->metrics['page_load'] as $page => $data) {
            if ($data['duration'] > 3) {
                $recommendations[] = "Page '{$page}' loads slowly ({$data['duration']}s)";
            }
            if ($data['size'] > 1000000) {
                $recommendations[] = "Page '{$page}' is too large (" . size_format($data['size']) . ")";
            }
        }

        // Database recommendations
        if ($this->metrics['database']['total_queries'] > 50) {
            $recommendations[] = "Too many database queries ({$this->metrics['database']['total_queries']})";
        }

        // Memory recommendations
        $memory_percent = ($this->metrics['memory']['peak'] / $this->metrics['memory']['limit']) * 100;
        if ($memory_percent > 80) {
            $recommendations[] = "High memory usage ({$memory_percent}% of limit)";
        }

        return $recommendations;
    }
}

// Schedule regular performance tests
if (!wp_next_scheduled('run_performance_test')) {
    wp_schedule_event(time(), 'daily', 'run_performance_test');
}

add_action('run_performance_test', function() {
    $tester = new Performance_Tester();
    $tester->run_tests();
});

Best Practices Checklist

Performance Optimization Checklist

## Server & Hosting
- [ ] Use PHP 8.0 or higher
- [ ] Enable OPcache
- [ ] Configure MySQL for performance
- [ ] Use HTTP/2 or HTTP/3
- [ ] Enable Gzip/Brotli compression
- [ ] Set up proper caching headers

## Caching
- [ ] Implement page caching
- [ ] Configure object caching (Redis/Memcached)
- [ ] Set up browser caching
- [ ] Use CDN for static assets
- [ ] Implement fragment caching for dynamic content

## Database
- [ ] Optimize database tables regularly
- [ ] Remove post revisions
- [ ] Clean up transients
- [ ] Add custom indexes for slow queries
- [ ] Limit autoloaded options

## Frontend
- [ ] Optimize images (WebP, responsive images)
- [ ] Minify CSS and JavaScript
- [ ] Implement critical CSS
- [ ] Defer non-critical JavaScript
- [ ] Lazy load images and videos
- [ ] Preload critical resources

## WordPress Specific
- [ ] Disable unnecessary plugins
- [ ] Use lightweight theme
- [ ] Limit external HTTP requests
- [ ] Optimize WP_Query usage
- [ ] Disable pingbacks and trackbacks
- [ ] Use efficient pagination

## Monitoring
- [ ] Set up performance monitoring
- [ ] Track Core Web Vitals
- [ ] Monitor error logs
- [ ] Set up uptime monitoring
- [ ] Regular performance audits

Conclusion

WordPress performance optimization is an ongoing process that requires attention to multiple layers of your stack. By implementing the techniques in this guide, you can achieve:

Remember that performance optimization is not a one-time task but an iterative process. Regular monitoring, testing, and optimization ensure your WordPress site remains fast as it grows and evolves.

Start with the basics—choose good hosting, implement caching, and optimize your database. Then progressively add advanced techniques based on your specific needs. The investment in performance pays dividends in user satisfaction, search rankings, and business success.


Master the complete WordPress development stack with our comprehensive guides on Gutenberg Development, Headless WordPress, and WooCommerce Development.