18 mars 2024 · Tommy Bordas

Optimisation des Performances WooCommerce

woocommercewordpressperformanceoptimisation

L'optimisation des performances est cruciale pour une boutique WooCommerce. Voici mes techniques éprouvées pour maximiser les performances tout en maintenant une excellente expérience utilisateur.

Optimisations Serveur

Configuration PHP

memory_limit = 256M
max_execution_time = 300
post_max_size = 64M
upload_max_filesize = 32M
max_input_vars = 3000

Configuration MySQL

innodb_buffer_pool_size = 1G
innodb_file_per_table = 1
innodb_flush_method = O_DIRECT
innodb_log_buffer_size = 16M
query_cache_size = 0

Cache Avancé

Object Cache Redis

define('WP_CACHE', true);
define('WP_REDIS_HOST', 'localhost');
define('WP_REDIS_PORT', 6379);

// Configuration du cache objet
wp_cache_add_global_groups([
    'woocommerce',
    'products',
    'orders'
]);

Cache Page Full-Page

class WC_Advanced_Cache {
    private $cache_path;
    
    public function __construct() {
        $this->cache_path = WP_CONTENT_DIR . '/cache/wc-pages/';
        add_action('template_redirect', [$this, 'cache_page']);
    }
    
    public function cache_page() {
        if ($this->is_cacheable()) {
            $cache_key = $this->generate_cache_key();
            $content = $this->get_cached_content($cache_key);
            
            if (!$content) {
                ob_start([$this, 'save_cache']);
            } else {
                echo $content;
                exit;
            }
        }
    }
}

Optimisation Base de Données

Nettoyage Automatique

class WC_DB_Optimizer {
    public function cleanup_old_data() {
        global $wpdb;
        
        // Supprimer les anciennes sessions
        $wpdb->query("
            DELETE FROM {$wpdb->prefix}woocommerce_sessions 
            WHERE session_expiry < UNIX_TIMESTAMP(NOW() - INTERVAL 30 DAY)
        ");
        
        // Nettoyer les méta-données orphelines
        $wpdb->query("
            DELETE pm FROM {$wpdb->postmeta} pm
            LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
            WHERE p.ID IS NULL
        ");
    }
}

Optimisation des Requêtes

class WC_Query_Optimizer {
    public function optimize_product_queries($query) {
        if (!is_admin() && $query->is_main_query() && is_shop()) {
            $query->set('no_found_rows', true);
            $query->set('posts_per_page', 24);
            $query->set('update_post_meta_cache', false);
            $query->set('update_post_term_cache', false);
        }
    }
}

Optimisation des Assets

Minification et Concaténation

add_action('wp_enqueue_scripts', function() {
    wp_enqueue_style(
        'wc-optimized',
        get_template_directory_uri() . '/assets/css/wc-optimized.min.css',
        [],
        THEME_VERSION
    );
    
    wp_enqueue_script(
        'wc-optimized',
        get_template_directory_uri() . '/assets/js/wc-optimized.min.js',
        ['jquery'],
        THEME_VERSION,
        true
    );
}, 20);

Lazy Loading Images

class WC_Image_Optimizer {
    public function optimize_product_images($html) {
        if (strpos($html, 'wp-post-image') !== false) {
            $html = preg_replace(
                '/src=["\'](.*?)["\']/',
                'src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="$1"',
                $html
            );
            $html = str_replace('class="', 'class="lazyload ', $html);
        }
        return $html;
    }
}

Optimisation du Checkout

Validation AJAX

class WC_Checkout_Optimizer {
    public function validate_fields() {
        add_action('wp_ajax_wc_validate_checkout', [$this, 'ajax_validate']);
        add_action('wp_ajax_nopriv_wc_validate_checkout', [$this, 'ajax_validate']);
    }
    
    public function ajax_validate() {
        $fields = $_POST['checkout_fields'] ?? [];
        $errors = [];
        
        foreach ($fields as $key => $value) {
            if (!$this->validate_field($key, $value)) {
                $errors[$key] = $this->get_error_message($key);
            }
        }
        
        wp_send_json([
            'valid' => empty($errors),
            'errors' => $errors
        ]);
    }
}

Monitoring et Analytics

Performance Tracking

class WC_Performance_Monitor {
    private $metrics = [];
    
    public function track_metric($name, $value) {
        $this->metrics[$name] = [
            'value' => $value,
            'timestamp' => microtime(true)
        ];
    }
    
    public function get_report() {
        return [
            'page_load' => $this->get_page_load_time(),
            'db_queries' => $this->get_db_query_count(),
            'memory_usage' => memory_get_peak_usage(true),
            'cache_hits' => wp_cache_get_stats()
        ];
    }
}

Résultats Obtenus

  1. Performance

    • Temps de chargement < 2s
    • Score PageSpeed > 90
    • TTFB < 200ms
  2. Base de Données

    • Réduction de 40% des requêtes
    • Optimisation des index
    • Nettoyage automatique
  3. Expérience Utilisateur

    • Chargement fluide
    • Navigation instantanée
    • Checkout optimisé

Conclusion

L'optimisation de WooCommerce est un processus continu qui nécessite une approche globale. Ces techniques permettent d'obtenir une boutique performante et une expérience utilisateur optimale.