Parcours Intermediaire : Ingenieur WordPress Production

Parcours Intermediaire : Ingenieur WordPress Production

Niveau: Intermediaire
Duree estimee: 12-16 semaines
Prerequis: Maitrise de WordPress, bases Linux/VPS, connaissance Git

Vue d’ensemble

Ce parcours vous transformera en ingenieur WordPress Production capable de gerer des infrastructures haute performance, implementer des pipelines CI/CD avec GitHub Actions, securiser des environnements critiques et optimiser des sites a grande echelle. Vous apprendrez a integrer des workflows assistes par IA (Claude.ai, ChatGPT) pour accelerer votre productivite.

Phase 1 : Infrastructure VPS & Stack Haute Performance

Objectifs

  • Maitriser le deploiement d’un stack WordPress optimise sur VPS Debian
  • Configurer WordOps pour une gestion simplifiee
  • Implementer un systeme de cache multi-couches
  • Optimiser les performances au niveau noyau Linux
  • Competences techniques

    1.1 Preparation VPS Debian

    Technologies: Debian 11/12, SSH, UFW, Fail2Ban

    Configuration initiale securisee:

    Mise a jour systeme

    apt update && apt upgrade -y

    Configuration utilisateur non-root

    adduser deployuser usermod -aG sudo deployuser

    Securisation SSH

    sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshdconfig sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshdconfig systemctl restart sshd

    Firewall UFW

    ufw default deny incoming ufw default allow outgoing ufw allow 22/tcp ufw allow 80/tcp ufw allow 443/tcp ufw enable

    Ressources:

  • Guide Debian Security
  • Documentation officielle UFW
  • 1.2 Installation et configuration WordOps

    Technologies: WordOps 3.x, Nginx, PHP 8.2/8.3, MariaDB 10.11, Redis 7.x

    Installation WordOps (2025):

    Installation

    wget -qO wo wops.cc && sudo bash wo

    Verification

    wo --version

    WordOps 3.x.x

    Stack complet

    wo stack install wo stack install --php82 --php83 wo stack install --redis

    Note importante: Des problemes d’installation ont ete reportes sur Debian 12.10 debut 2025. Verifiez le forum communautaire WordOps pour les dernieres mises a jour de compatibilite.

    Creation de site optimise:

    Site WordPress avec cache Redis et Let's Encrypt

    wo site create example.com --wp --php83 --redis --letsencrypt

    Verification configuration Nginx

    wo site info example.com

    Caracteristiques WordOps:

  • TTFB < 100 ms sur VPS economiques
  • Support HTTP/3 QUIC integre
  • Optimisations noyau Linux automatiques
  • Certificats SSL/TLS wildcard avec validation DNS
  • Ressources:

  • WordOps Documentation Officielle
  • Guide WordOps VPS – Linux Nest
  • 1.3 Cache multi-couches : Nginx FastCGI + Redis Object Cache

    A. Nginx FastCGI Cache

    Le cache FastCGI permet a Nginx de servir directement le HTML genere par PHP-FPM sans solliciter WordPress, PHP ou MySQL pour les requetes suivantes.

    Configuration Nginx (/etc/nginx/conf.d/fastcgi-cache.conf):

    Zone de cache

    fastcgicachepath /var/run/nginx-cache levels=1:2 keyszone=WORDPRESS:100m inactive=60m maxsize=500m; fastcgicachekey "$scheme$requestmethod$host$requesturi"; fastcgicacheusestale error timeout invalidheader http500; fastcgiignoreheaders Cache-Control Expires Set-Cookie;

    Dans votre configuration de site:

    Conditions de bypass

    set $skip
    cache 0; if ($requestmethod = POST) { set $skipcache 1; } if ($querystring != "") { set $skipcache 1; } if ($requesturi ~ "/wp-admin/|/xmlrpc.php|wp-..php|/feed/|sitemap(index)?.xml") { set $skipcache 1; } if ($httpcookie ~ "commentauthor|wordpress[a-f0-9]+|wp-postpass|wordpressloggedin") { set $skipcache 1; }

    Application du cache

    fastcgi
    cachebypass $skipcache; fastcginocache $skipcache; fastcgicache WORDPRESS; fastcgicachevalid 200 60m; fastcgicachevalid 404 10m; addheader X-FastCGI-Cache $upstreamcachestatus;

    Plugin WordPress recommande:

  • Nginx Cache Purge Preload (NPP) – Gestion directe des fichiers cache sans modules Nginx
  • B. Redis Object Cache

    Redis reduit de jusqu’a 80% les requetes base de donnees en stockant en memoire les resultats frequemment demandes.

    Configuration Redis (/etc/redis/redis.conf):

    Memoire allouee (minimum 256MB production)

    maxmemory 512mb maxmemory-policy allkeys-lru

    Persistence

    save 900 1 save 300 10 save 60 10000

    Performance

    tcp-backlog 511 timeout 0 tcp-keepalive 300

    Configuration WordPress (wp-config.php):

    define('WPREDISHOST', '127.0.0.1');
    define('WPREDISPORT', 6379);
    define('WPREDISDATABASE', 0);
    define('WPREDISMAXTTL', 86400); // 24 heures
    
    // Options recommandees
    define('WPREDISTIMEOUT', 1);
    define('WPREDISREADTIMEOUT', 1);
    

    Plugins recommandes:

  • Redis Object Cache (gratuit) – Supporte Predis, PhpRedis, Relay, clustering
  • Object Cache Pro (premium) – 1500+ tests, optimise WooCommerce, PHP 7.2-8.4
  • TTL recommandes (2025):

  • Donnees dynamiques (paniers, sessions): 60-300 secondes
  • Menus, options site: 3600-86400 secondes
  • Taxonomies, termes: 7200 secondes
  • Verification performances:

    Stats Redis

    redis-cli INFO stats

    Monitoring en temps reel

    redis-cli MONITOR

    Via WP-CLI

    wp redis status wp redis info

    Cas d’usage optimaux:

  • E-commerce (WooCommerce)
  • Sites membres
  • Forums et communautes
  • Sites haute concurrence (>10000 visiteurs/jour)
  • Attention: Pour les petits blogs avec cache page-level efficace et trafic faible, Redis peut compliquer inutilement votre stack.

    Ressources:

  • Redis Object Cache Plugin
  • Guide Nginx FastCGI 2025 – DoHost
  • Redis WordPress 2025 – Boosted Host
  • 1.4 Optimisations serveur avancees

    PHP 8.3 OPcache configuration (/etc/php/8.3/fpm/conf.d/10-opcache.ini):

    opcache.enable=1
    opcache.memoryconsumption=256
    opcache.internedstringsbuffer=16
    opcache.maxacceleratedfiles=10000
    opcache.revalidatefreq=2
    opcache.fastshutdown=1
    opcache.enablecli=0
    
    

    Performance optimale (maintenir proche de 100%)

    opcache.validatetimestamps=0

    Monitoring OPcache:

    Via WP-CLI

    wp opcache status

    Configuration PHP-FPM (/etc/php/8.3/fpm/pool.d/www.conf):

    ; Process manager
    pm = dynamic
    pm.maxchildren = 50
    pm.startservers = 10
    pm.minspareservers = 5
    pm.maxspareservers = 20
    pm.maxrequests = 500
    
    ; Monitoring
    pm.statuspath = /status
    ping.path = /ping
    

    Calcul memoire par worker:

    Memoire moyenne par process PHP-FPM

    ps --no-headers -o "rss,cmd" -C php-fpm8.3 | awk '{ sum+=$1 } END { printf ("%d%sn", sum/NR/1024,"M") }'

    Formule: RAMdisponible / Memoireparprocess = pm.maxchildren

    Optimisations noyau Linux (/etc/sysctl.conf):

    Network performance

    net.core.somaxconn = 65535 net.ipv4.tcp
    maxsynbacklog = 8192 net.ipv4.tcpfintimeout = 30 net.ipv4.tcpkeepalivetime = 300 net.ipv4.tcpkeepaliveintvl = 30 net.ipv4.tcpkeepaliveprobes = 3

    File descriptors

    fs.file-max = 100000

    Application

    sysctl -p

    Requis materiels production (2025):

  • Minimum: 4vCPU / 4GB RAM / NVMe
  • Recommande: 8vCPU / 8GB RAM / NVMe RAID
  • Cache Redis: 256MB minimum, 512MB-1GB recommande
  • OPcache: 128MB minimum, 256MB recommande
  • Objectifs performance:

  • TTFB: < 100ms
  • LCP (Largest Contentful Paint): < 2.5s
  • FID (First Input Delay): < 100ms
  • CLS (Cumulative Layout Shift): < 0.1
  • Capacite: 500+ utilisateurs concurrents sur 2GB RAM (avec cache)
  • Projet pratique Phase 1

    Deploiement infrastructure complete:

  • Provisionner un VPS Debian 11/12 (4GB RAM minimum)
  • Securiser le serveur (SSH, firewall, fail2ban)
  • Installer WordOps avec stack complet
  • Creer un site WordPress avec Redis et SSL
  • Configurer cache Nginx FastCGI + Redis Object Cache
  • Optimiser PHP-FPM et OPcache
  • Effectuer des tests de charge (ApacheBench, k6)
  • Documenter votre configuration et resultats de performance
  • Benchmark attendus:

  • TTFB < 100ms
  • 1000 req/s sans degradation
  • Taux hit cache > 90%
  • Phase 2 : Securite Production & Hardening

    Objectifs

  • Implementer les techniques de hardening WordPress 2025
  • Configurer un WAF applicatif
  • Automatiser les audits de securite
  • Gerer les vulnerabilites et mises a jour
  • Contexte menaces 2025

    Statistiques critiques:

  • 7,966 vulnerabilites decouvertes dans l’ecosysteme WordPress en 2024 (+34% vs 2023)
  • Les plugins populaires (WooCommerce, LiteSpeed Cache, The Events Calendar) sont des cibles prioritaires
  • 87.8% des attaques testees contournent les defenses niveau hebergeur
  • Le delai de mise a jour cree les degats, pas l’absence de patches
  • Source: Patchstack Q3 2025 Report

    Competences techniques

    2.1 Hardening wp-config.php

    Configuration securisee complete:

    
      WordPress Configuration securisee - Production 2025
     /
    
    // === CLES DE SECURITE ===
    // Generees via https://api.wordpress.org/secret-key/1.1/salt/
    define('AUTHKEY',         'votre-cle-unique-generee');
    define('SECUREAUTHKEY',  'votre-cle-unique-generee');
    define('LOGGEDINKEY',    'votre-cle-unique-generee');
    define('NONCEKEY',        'votre-cle-unique-generee');
    define('AUTHSALT',        'votre-cle-unique-generee');
    define('SECUREAUTHSALT', 'votre-cle-unique-generee');
    define('LOGGEDINSALT',   'votre-cle-unique-generee');
    define('NONCESALT',       'votre-cle-unique-generee');
    
    // === SECURITE PRODUCTION ===
    // Desactiver editeur de fichiers
    define('DISALLOWFILEEDIT', true);
    define('DISALLOWFILEMODS', true);
    
    // Limiter revisions
    define('WPPOSTREVISIONS', 5);
    define('AUTOSAVEINTERVAL', 300);
    
    // Vider corbeille automatiquement
    define('EMPTYTRASHDAYS', 7);
    
    // Forcer SSL admin
    define('FORCESSLADMIN', true);
    
    // Bloquer requetes externes (sauf services approuves)
    define('WPHTTPBLOCKEXTERNAL', true);
    define('WPACCESSIBLEHOSTS', 'api.wordpress.org,.github.com,.cloudflare.com');
    
    // === PERFORMANCE ===
    define('WPMEMORYLIMIT', '256M');
    define('WPMAXMEMORYLIMIT', '512M');
    define('WPCACHE', true);
    
    // === MODE DEBUG (DESACTIVE EN PRODUCTION) ===
    define('WPDEBUG', false);
    define('WPDEBUGLOG', false);
    define('WPDEBUGDISPLAY', false);
    define('SCRIPTDEBUG', false);
    @iniset('displayerrors', 0);
    
    // === BASE DE DONNEES ===
    define('DBNAME', 'databasename');
    define('DBUSER', 'databaseuser');
    define('DBPASSWORD', 'strongpasswordhere');
    define('DBHOST', 'localhost');
    define('DBCHARSET', 'utf8mb4');
    define('DBCOLLATE', '');
    $tableprefix = 'wp'; // Changer pour prefixe unique en production
    
    // === SECURITE COOKIES ===
    define('COOKIEDOMAIN', 'example.com');
    define('COOKIEPATH', '/');
    define('SITECOOKIEPATH', '/');
    define('ADMINCOOKIEPATH', SITECOOKIEPATH . 'wp-admin');
    
    // === PARAMETRES AVANCES ===
    define('CONCATENATESCRIPTS', false); // Desactive si HTTP/2 actif
    define('COMPRESSSCRIPTS', true);
    define('COMPRESSCSS', true);
    
    / C'est tout, ne modifiez pas ce qui suit ! Bonne publication. /
    if ( ! defined( 'ABSPATH' ) ) {
        define( 'ABSPATH', DIR . '/' );
    }
    requireonce ABSPATH . 'wp-settings.php';
    

    Rotation cles de securite (recommande tous les 3-6 mois):

    Generer nouvelles cles

    curl -s https://api.wordpress.org/secret-key/1.1/salt/

    2.2 Permissions fichiers et verrouillage systeme

    Permissions optimales:

    Repertoires

    find /var/www/example.com/htdocs -type d -exec chmod 755 {} ;

    Fichiers

    find /var/www/example.com/htdocs -type f -exec chmod 644 {} ;

    wp-config.php ultra-securise

    chmod 440 /var/www/example.com/htdocs/wp-config.php chown www-data:www-data /var/www/example.com/htdocs/wp-config.php

    .htaccess

    chmod 444 /var/www/example.com/htdocs/.htaccess

    Verrouillage immutabilite (fichiers critiques):

    Rendre wp-config.php immuable

    chattr +i /var/www/example.com/htdocs/wp-config.php

    Verification

    lsattr /var/www/example.com/htdocs/wp-config.php

    Retirer l'immutabilite (pour modification)

    chattr -i /var/www/example.com/htdocs/wp-config.php

    Protection repertoires sensibles (Nginx):

    Bloquer acces wp-config.php

    location ~
    wp-config.php { deny all; }

    Bloquer fichiers sensibles

    location ~ .(log|sql|conf|bak|old|git)$ { deny all; }

    Limiter acces wp-login.php par IP (optionnel)

    location = /wp-login.php { allow 203.0.113.0/24; # Votre IP deny all; include fastcgi
    params; fastcgipass php; }

    2.3 Protection authentification avancee

    A. Authentification a deux facteurs (2FA)

    Plugins recommandes:

  • Two Factor Authentication (gratuit)
  • Wordfence Security (freemium) – Inclut 2FA + WAF
  • WP 2FA (premium)
  • Configuration via WP-CLI:

    Installer plugin 2FA

    wp plugin install two-factor --activate

    Forcer 2FA pour tous les administrateurs

    wp user meta update USER
    ID twofactorrequired 1

    B. Limitation tentatives connexion

    Plugin: Limit Login Attempts Reloaded

    Configuration Nginx (alternative):

    Rate limiting connexions

    limitreqzone $binaryremoteaddr zone=login:10m rate=5r/m; location = /wp-login.php { limitreq zone=login burst=2 nodelay; include fastcgiparams; fastcgipass php; }

    C. Renommer URL admin

    Plugin: WPS Hide Login

    Avantages:

  • Reduit drastiquement attaques brute-force automatisees
  • Masque /wp-admin et /wp-login.php
  • Configuration simple via interface
  • 2.4 Web Application Firewall (WAF) niveau application

    Solutions 2025:

    1. Patchstack (Recommande)

  • Mitigation couche application (RapidMitigate)
  • Bloque 87.8%+ des exploits WordPress
  • Base de donnees vulnerabilites temps reel
  • Protection virtuelle avant patch officiel
  • 2. Wordfence

  • WAF + scanner vulnerabilites
  • Protection brute-force integree
  • Monitoring temps reel
  • 3. Cloudflare WAF (Niveau edge)

  • Protection DDoS
  • Rate limiting global
  • Rules personnalisables
  • Configuration Cloudflare Rules (exemples):

    Bloquer scanners connus

    (http.user
    agent contains "nikto") or (http.useragent contains "sqlmap") or (http.useragent contains "masscan") Action: Block

    Rate limiting aggressif wp-login

    (http.request.uri.path eq "/wp-login.php") Action: Rate Limit (5 requests / 5 minutes)

    Bloquer acces xmlrpc.php

    (http.request.uri.path eq "/xmlrpc.php") Action: Block

    Configuration Wordfence recommandee:

    // wp-config.php
    define('WFWAFENABLED', true);
    define('WFWAFLOGATTACKS', true);
    define('WFWAFSTORAGEENGINE', 'mysqli');
    

    2.5 Discipline mises a jour et gestion vulnerabilites

    Strategie mise a jour 2025:

    1. Surveillance vulnerabilites

    WP-CLI - Verifier vulnerabilites connues

    wp plugin list --field=name | xargs -I {} wp plugin verify-checksums {}

    Vulnerabilite scan automatise

    wp vuln check

    2. Automatisation mises a jour mineures

    // wp-config.php - Activer mises a jour auto securite
    define('WPAUTOUPDATECORE', 'minor');
    
    // Auto-update plugins de securite
    addfilter('autoupdateplugin', 'returntrue');
    

    3. Workflow mise a jour production

    Processus recommande:

  • Staging: Tester mise a jour sur environnement clone
  • Verification: Tester fonctionnalites critiques
  • Backup: Sauvegarde complete base + fichiers
  • Mise a jour production: Fenetre maintenance
  • Monitoring: Surveiller erreurs 24-48h
  • Script backup pre-update:

    #!/bin/bash
    SITE="example.com"
    DATE=$(date +%Y%m%d%H%M%S)
    BACKUPDIR="/backups/$SITE"
    
    

    Backup base de donnees

    wp db export "$BACKUPDIR/db$DATE.sql" --path=/var/www/$SITE/htdocs

    Backup fichiers

    tar -czf "$BACKUPDIR/files$DATE.tar.gz" -C /var/www/$SITE htdocs

    Garder 7 derniers backups

    find "$BACKUPDIR" -name ".sql" -mtime +7 -delete find "$BACKUP
    DIR" -name ".tar.gz" -mtime +7 -delete echo "Backup complete: $DATE"

    4. Monitoring post-update

    Verifier erreurs PHP

    tail -f /var/log/php8.3-fpm.log

    Verifier erreurs Nginx

    tail -f /var/log/nginx/error.log

    Monitoring WordPress

    wp core verify-checksums

    2.6 Headers de securite HTTP

    Configuration Nginx (/etc/nginx/common/wpcommon.conf):

    Security headers

    addheader X-Frame-Options "SAMEORIGIN" always; addheader X-Content-Type-Options "nosniff" always; addheader X-XSS-Protection "1; mode=block" always; addheader Referrer-Policy "strict-origin-when-cross-origin" always;

    CSP (Content Security Policy) - Adapter a votre site

    addheader Content-Security-Policy "default-src 'self' https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'self';" always;

    HSTS (HTTP Strict Transport Security) - Attention: preload permanent

    add
    header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    Permissions Policy

    addheader Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

    Verification headers:

    curl -I https://example.com | grep -E "(X-Frame|X-Content|Strict-Transport)"
    

    Outils audit:

  • SecurityHeaders.com
  • Mozilla Observatory
  • Projet pratique Phase 2

    Audit et hardening securite complet:

  • Auditer site existant avec WPScan et Wordfence
  • Implementer toutes configurations hardening wp-config.php
  • Configurer permissions fichiers optimales
  • Installer et configurer 2FA pour tous admins
  • Deployer WAF (Wordfence ou Patchstack)
  • Configurer headers securite HTTP
  • Mettre en place processus backup pre-update
  • Tester tentatives intrusion et verifier blocages
  • Documenter toutes procedures securite
  • Livrable: Documentation securite complete + rapport audit avant/apres

    Ressources:

  • WordPress Security Hardening 2025 – Security Ninja
  • WordPress Developer Handbook – Hardening
  • 30+ Best Practices 2025 – WP Umbrella
  • Phase 3 : CI/CD avec GitHub Actions

    Objectifs

  • Maitriser Git workflows pour WordPress
  • Implementer pipelines CI/CD automatises
  • Deployer automatiquement via GitHub Actions
  • Integrer tests automatises
  • Competences techniques

    3.1 Structure repository Git pour WordPress

    Architecture recommandee:

    mon-site-wordpress/
    ├── .github/
    │   ├── workflows/
    │   │   ├── deploy-production.yml
    │   │   ├── deploy-staging.yml
    │   │   └── code-quality.yml
    ├── wp-content/
    │   ├── themes/
    │   │   └── mon-theme/
    │   ├── plugins/
    │   │   └── mon-plugin/
    │   └── mu-plugins/
    ├── config/
    │   ├── wp-config-production.php
    │   ├── wp-config-staging.php
    │   └── nginx/
    │       └── site.conf
    ├── scripts/
    │   ├── deploy.sh
    │   └── backup.sh
    ├── tests/
    │   ├── phpunit/
    │   └── e2e/
    ├── .gitignore
    ├── composer.json
    ├── package.json
    └── README.md
    

    .gitignore optimise WordPress:

    WordPress core

    /wp-admin/ /wp-includes/ wp-
    .php xmlrpc.php readme.html license.txt

    Configuration

    wp-config.php .htaccess

    Uploads et cache

    wp-content/uploads/ wp-content/cache/ wp-content/upgrade/

    Plugins et themes tiers (geres via composer)

    wp-content/plugins/ !wp-content/plugins/mon-plugin/ wp-content/themes/ !wp-content/themes/mon-theme/

    Dependencies

    /vendor/ /node
    modules/

    OS et IDE

    .DSStore Thumbs.db .idea/ .vscode/ .swp

    Backups

    .sql .sql.gz .tar.gz

    composer.json pour dependencies:

    {
        "name": "example/mon-site",
        "description": "Site WordPress production",
        "type": "project",
        "require": {
            "php": ">=8.2",
            "composer/installers": "^2.0",
            "wpackagist-plugin/redis-cache": "^2.5",
            "wpackagist-plugin/wordfence": "^7.11"
        },
        "require-dev": {
            "phpunit/phpunit": "^10.0",
            "squizlabs/phpcodesniffer": "^3.7",
            "phpstan/phpstan": "^1.10"
        },
        "repositories": [
            {
                "type": "composer",
                "url": "https://wpackagist.org"
            }
        ],
        "extra": {
            "installer-paths": {
                "wp-content/plugins/{$name}/": ["type:wordpress-plugin"],
                "wp-content/themes/{$name}/": ["type:wordpress-theme"]
            }
        }
    }
    

    3.2 GitHub Actions workflow – Deploiement Staging

    .github/workflows/deploy-staging.yml:

    name: Deploy to Staging
    
    on:
      push:
        branches:
          - develop
    
    env:
      SSHHOST: ${{ secrets.STAGINGSSHHOST }}
      SSHUSER: ${{ secrets.STAGINGSSHUSER }}
      SSHPORT: ${{ secrets.STAGINGSSHPORT }}
      DEPLOYPATH: /var/www/staging.example.com/htdocs
    
    jobs:
      deploy:
        name: Deploy to Staging Server
        runs-on: ubuntu-latest
    
        steps:
          - name: Checkout code
            uses: actions/checkout@v4
    
          - name: Setup PHP
            uses: shivammathur/setup-php@v2
            with:
              php-version: '8.3'
              extensions: mbstring, xml, zip
              tools: composer:v2
    
          - name: Setup Node.js
            uses: actions/setup-node@v4
            with:
              node-version: '20'
              cache: 'npm'
    
          - name: Install Composer dependencies
            run: |
              composer install --no-dev --optimize-autoloader --no-interaction
    
          - name: Install NPM dependencies and build
            run: |
              npm ci
              npm run build
    
          - name: Run PHP CodeSniffer
            run: |
              vendor/bin/phpcs --standard=PSR12 wp-content/themes/mon-theme
              vendor/bin/phpcs --standard=WordPress wp-content/plugins/mon-plugin
    
          - name: Run PHPStan
            run: vendor/bin/phpstan analyse wp-content/themes/mon-theme wp-content/plugins/mon-plugin
    
          - name: Setup SSH key
            uses: webfactory/ssh-agent@v0.9.0
            with:
              ssh-private-key: ${{ secrets.STAGINGSSHPRIVATEKEY }}
    
          - name: Add server to known hosts
            run: |
              mkdir -p ~/.ssh
              ssh-keyscan -p $SSHPORT -H $SSHHOST >> ~/.ssh/knownhosts
    
          - name: Deploy via rsync
            run: |
              rsync -avz 
                --delete 
                --exclude='.git' 
                --exclude='.github' 
                --exclude='nodemodules' 
                --exclude='tests' 
                --exclude='wp-config.php' 
                --exclude='wp-content/uploads' 
                --exclude='wp-content/cache' 
                -e "ssh -p $SSHPORT" 
                ./ $SSHUSER@$SSHHOST:$DEPLOYPATH/
    
          - name: Run post-deployment commands
            run: |
              ssh -p $SSHPORT $SSHUSER@$SSHHOST << 'ENDSSH'
                cd ${{ env.DEPLOYPATH }}
    
                # Composer autoload
                composer dump-autoload --optimize --no-dev
    
                # WP-CLI operations
                wp cache flush --allow-root
                wp rewrite flush --allow-root
    
                # Permissions
                find . -type f -exec chmod 644 {} ;
                find . -type d -exec chmod 755 {} ;
    
                # Redis cache clear
                wp redis cli FLUSHDB --allow-root
    
                echo "Deployment complete!"
              ENDSSH
    
          - name: Notify deployment
            if: always()
            run: |
              echo "Staging deployment finished: ${{ job.status }}"
              # Integration Slack/Discord possible ici
    

    3.3 GitHub Actions workflow – Deploiement Production

    .github/workflows/deploy-production.yml:

    name: Deploy to Production
    
    on:
      push:
        branches:
          - main
      workflowdispatch: # Permet declenchement manuel
    
    env:
      SSHHOST: ${{ secrets.PRODSSHHOST }}
      SSHUSER: ${{ secrets.PRODSSHUSER }}
      SSHPORT: ${{ secrets.PRODSSHPORT }}
      DEPLOYPATH: /var/www/example.com/htdocs
    
    jobs:
      test:
        name: Run Tests
        runs-on: ubuntu-latest
    
        steps:
          - name: Checkout code
            uses: actions/checkout@v4
    
          - name: Setup PHP
            uses: shivammathur/setup-php@v2
            with:
              php-version: '8.3'
              extensions: mbstring, xml, zip, mysql
    
          - name: Install dependencies
            run: composer install --no-interaction
    
          - name: Run PHPUnit tests
            run: vendor/bin/phpunit tests/
    
          - name: Run PHP CodeSniffer
            run: vendor/bin/phpcs --standard=WordPress wp-content/themes/ wp-content/plugins/
    
          - name: Run PHPStan
            run: vendor/bin/phpstan analyse --level=5 wp-content/themes/ wp-content/plugins/
    
      backup:
        name: Backup Production
        runs-on: ubuntu-latest
        needs: test
    
        steps:
          - name: Setup SSH key
            uses: webfactory/ssh-agent@v0.9.0
            with:
              ssh-private-key: ${{ secrets.PRODSSHPRIVATEKEY }}
    
          - name: Create backup
            run: |
              ssh -p $SSHPORT $SSHUSER@$SSHHOST << 'ENDSSH'
                BACKUPDIR="/backups/example.com"
                DATE=$(date +%Y%m%d%H%M%S)
    
                # Database backup
                wp db export "$BACKUPDIR/pre-deploy$DATE.sql" 
                  --path=${{ env.DEPLOYPATH }} 
                  --allow-root
    
                # Files backup
                tar -czf "$BACKUPDIR/files$DATE.tar.gz" 
                  -C ${{ env.DEPLOYPATH }} 
                  wp-content/themes/mon-theme 
                  wp-content/plugins/mon-plugin
    
                echo "Backup created: $DATE"
              ENDSSH
    
      deploy:
        name: Deploy to Production
        runs-on: ubuntu-latest
        needs: backup
        environment:
          name: production
          url: https://example.com
    
        steps:
          - name: Checkout code
            uses: actions/checkout@v4
    
          - name: Setup PHP
            uses: shivammathur/setup-php@v2
            with:
              php-version: '8.3'
    
          - name: Setup Node.js
            uses: actions/setup-node@v4
            with:
              node-version: '20'
    
          - name: Build assets
            run: |
              composer install --no-dev --optimize-autoloader
              npm ci
              npm run build:production
    
          - name: Setup SSH key
            uses: webfactory/ssh-agent@v0.9.0
            with:
              ssh-private-key: ${{ secrets.PRODSSHPRIVATEKEY }}
    
          - name: Enable maintenance mode
            run: |
              ssh -p $SSHPORT $SSHUSER@$SSHHOST << 'ENDSSH'
                wp maintenance-mode activate --allow-root 
                  --path=${{ env.DEPLOYPATH }}
              ENDSSH
    
          - name: Deploy files
            run: |
              rsync -avz 
                --delete 
                --exclude='.git' 
                --exclude='nodemodules' 
                --exclude='wp-config.php' 
                --exclude='wp-content/uploads' 
                -e "ssh -p $SSHPORT" 
                ./ $SSHUSER@$SSHHOST:$DEPLOYPATH/
    
          - name: Post-deployment tasks
            run: |
              ssh -p $SSHPORT $SSHUSER@$SSHHOST << 'ENDSSH'
                cd ${{ env.DEPLOYPATH }}
    
                # Database migration (si necessaire)
                # wp migrate --allow-root
    
                # Clear all caches
                wp cache flush --allow-root
                wp rewrite flush --allow-root
    
                # Redis flush
                wp redis cli FLUSHDB --allow-root
    
                # Nginx cache purge
                rm -rf /var/run/nginx-cache/
    
                # OPcache reset
                wp opcache reset --allow-root
    
                # Permissions
                find wp-content/themes/mon-theme -type f -exec chmod 644 {} ;
                find wp-content/plugins/mon-plugin -type f -exec chmod 644 {} ;
    
                echo "Post-deployment complete"
              ENDSSH
    
          - name: Disable maintenance mode
            if: always()
            run: |
              ssh -p $SSHPORT $SSHUSER@$SSHHOST << 'ENDSSH'
                wp maintenance-mode deactivate --allow-root 
                  --path=${{ env.DEPLOYPATH }}
              ENDSSH
    
          - name: Health check
            run: |
              RESPONSE=$(curl -s -o /dev/null -w "%{httpcode}" https://example.com)
              if [ $RESPONSE -ne 200 ]; then
                echo "Health check failed! HTTP $RESPONSE"
                exit 1
              fi
              echo "Health check passed: HTTP $RESPONSE"
    
          - name: Notify deployment success
            if: success()
            run: echo "Production deployment successful!"
    
          - name: Notify deployment failure
            if: failure()
            run: echo "Production deployment failed! Rolling back..."
    

    3.4 Workflow qualite code

    .github/workflows/code-quality.yml:

    name: Code Quality Checks
    
    on:
      pullrequest:
        branches:
          - develop
          - main
    
    jobs:
      code-quality:
        name: Code Quality
        runs-on: ubuntu-latest
    
        steps:
          - name: Checkout code
            uses: actions/checkout@v4
    
          - name: Setup PHP
            uses: shivammathur/setup-php@v2
            with:
              php-version: '8.3'
              coverage: xdebug
    
          - name: Install dependencies
            run: composer install --no-interaction
    
          - name: PHP CodeSniffer
            run: |
              vendor/bin/phpcs 
                --standard=WordPress 
                --extensions=php 
                --ignore=vendor 
                wp-content/
    
          - name: PHPStan Static Analysis
            run: vendor/bin/phpstan analyse --level=6 wp-content/
    
          - name: PHPUnit with Coverage
            run: vendor/bin/phpunit --coverage-text tests/
    
          - name: Check WordPress Coding Standards
            run: |
              composer require --dev wp-coding-standards/wpcs
              vendor/bin/phpcs --config-set installedpaths vendor/wp-coding-standards/wpcs
              vendor/bin/phpcs --standard=WordPress-Core wp-content/themes/
              vendor/bin/phpcs --standard=WordPress-Extra wp-content/plugins/
    

    3.5 Configuration secrets GitHub

    Secrets a configurer dans GitHub (Settings > Secrets and variables > Actions):

    Staging:

  • STAGINGSSHHOST: staging.example.com
  • STAGINGSSHUSER: deployuser
  • STAGINGSSHPORT: 22
  • STAGINGSSHPRIVATEKEY: Cle SSH privee (format PEM)
  • Production:

  • PRODSSHHOST: example.com
  • PRODSSHUSER: deployuser
  • PRODSSHPORT: 22
  • PRODSSHPRIVATEKEY: Cle SSH privee (format PEM)
  • Generation paire cles SSH pour deploiement:

    Sur votre machine locale

    ssh-keygen -t ed25519 -C "github-actions-deploy" -f ~/.ssh/github
    deploykey

    Copier cle publique sur serveur

    ssh-copy-id -i ~/.ssh/github
    deploykey.pub deployuser@example.com

    Copier cle privee dans GitHub Secrets

    cat ~/.ssh/github
    deploykey

    3.6 Deploiement avec Deployer.org (alternative)

    Installation Deployer:

    composer require --dev deployer/deployer
    

    deploy.php configuration:

    releases', 3);
    set('writablemode', 'chmod');
    set('writablechmodmode', '0755');
    
    // Serveurs
    host('production')
        ->setHostname('example.com')
        ->setRemoteUser('deployuser')
        ->setDeployPath('/var/www/example.com')
        ->set('branch', 'main')
        ->set('httpuser', 'www-data');
    
    host('staging')
        ->setHostname('staging.example.com')
        ->setRemoteUser('deployuser')
        ->setDeployPath('/var/www/staging.example.com')
        ->set('branch', 'develop')
        ->set('httpuser', 'www-data');
    
    // Fichiers partages entre deploiements
    set('sharedfiles', [
        'wp-config.php',
        '.htaccess'
    ]);
    
    set('shareddirs', [
        'wp-content/uploads',
        'wp-content/cache'
    ]);
    
    // Fichiers a exclure
    set('writabledirs', [
        'wp-content/uploads',
        'wp-content/cache'
    ]);
    
    // Tasks personnalisees
    desc('Clear WordPress cache');
    task('wp:cache:clear', function () {
        run('cd {{releasepath}} && wp cache flush --allow-root');
        run('cd {{releasepath}} && wp redis cli FLUSHDB --allow-root');
    });
    
    desc('Clear Nginx FastCGI cache');
    task('nginx:cache:clear', function () {
        run('rm -rf /var/run/nginx-cache/');
    });
    
    desc('Backup database before deploy');
    task('wp:db:backup', function () {
        $date = date('YmdHis');
        run("wp db export /backups/{{application}}/db$date.sql --path={{deploypath}}/current --allow-root");
    });
    
    // Workflow deploiement
    desc('Deploy WordPress');
    task('deploy', [
        'deploy:prepare',
        'wp:db:backup',
        'deploy:vendors',
        'deploy:publish',
        'wp:cache:clear',
        'nginx:cache:clear',
        'deploy:cleanup'
    ]);
    
    after('deploy:failed', 'deploy:unlock');
    

    GitHub Actions avec Deployer:

    - name: Deploy with Deployer
      run: |
        vendor/bin/dep deploy production 
          --branch=main 
          -vvv
    

    Projet pratique Phase 3

    Mise en place CI/CD complete:

  • Initialiser repository Git avec structure recommandee
  • Configurer .gitignore et composer.json
  • Creer workflows GitHub Actions (staging + production)
  • Configurer secrets GitHub
  • Implementer tests PHPUnit basiques
  • Configurer PHP CodeSniffer avec standards WordPress
  • Tester deploiement sur staging via push develop
  • Tester deploiement production via push main
  • Implementer rollback automatique en cas d’echec
  • Documenter processus deploiement
  • Livrable: Repository Git fonctionnel + documentation CI/CD + captures deploys reussis

    Ressources:

  • GitHub Actions for WordPress – Axioned
  • rtCamp WordPress Deploy Action
  • Deploying WordPress with GitHub Actions – CSS Tricks
  • Phase 4 : Performance a Grande Echelle

    Objectifs

  • Optimiser pour sites haute concurrence (10000+ visiteurs/jour)
  • Implementer CDN et optimisations edge
  • Maitriser monitoring et observabilite
  • Gerer bases de donnees volumineuses
  • Competences techniques

    4.1 Core Web Vitals et optimisation 2025

    Metriques critiques Google (impact SEO):

  • LCP (Largest Contentful Paint): < 2.5s (bon)
  • FID (First Input Delay): < 100ms (bon)
  • CLS (Cumulative Layout Shift): < 0.1 (bon)
  • TTFB (Time to First Byte): < 600ms (bon), < 200ms (excellent)
  • INP (Interaction to Next Paint): < 200ms (remplace FID en 2024)
  • Impact business:

  • 1 seconde de delai = -7% conversions
  • 53% utilisateurs mobiles abandonnent si chargement > 3s
  • Attention moyenne utilisateur: 8.25 secondes (2025)
  • Source: 15 WordPress Performance Tips 2025 – Odd Jar

    4.2 Optimisation images moderne

    A. Formats modernes (2025)

    AVIF (recommande):

  • Support WordPress Core natif (depuis WP 6.5)
  • Compression superieure a WebP (-30% vs WebP, -50% vs JPEG)
  • Support navigateurs: Chrome 85+, Firefox 93+, Safari 16+
  • WebP (fallback):

  • Support universel navigateurs modernes
  • -25-35% taille vs JPEG qualite equivalente
  • Configuration serveur Nginx:

    Servir AVIF si supporte

    location ~ .(jpg|jpeg|png)$ { set $avifsuffix ""; if ($httpaccept ~ "image/avif") { set $avif
    suffix ".avif"; } addheader Vary Accept; tryfiles $uri$avifsuffix $uri.webp $uri =404; }

    B. Plugins optimisation images

    Recommandes 2025:

  • Imagify (freemium) – Compression intelligente multi-format
  • ShortPixel (freemium) – AVIF + WebP + lazy loading
  • Smush (freemium) – Compression sans perte qualite
  • Configuration via WP-CLI:

    Installer Imagify

    wp plugin install imagify --activate

    Configuration API

    wp option update imagify
    settings '{"apikey":"YOURKEY","optimizationlevel":1,"autooptimize":1,"resizelarger":1,"resizelargerw":1920}'

    Optimiser bibliotheque existante (batch)

    wp imagify optimize --path=/var/www/example.com/htdocs

    C. Lazy loading natif WordPress

    // Actif par defaut depuis WP 5.5
    // Desactiver si conflit avec plugin tiers
    addfilter('wplazyloadingenabled', 'returnfalse');
    

    D. Responsive images (srcset)

    WordPress genere automatiquement srcset. Verification:

    // functions.php - Ajouter tailles personnalisees
    addimagesize('hero-desktop', 1920, 1080, true);
    addimagesize('hero-tablet', 1024, 768, true);
    addimagesize('hero-mobile', 640, 480, true);
    
    // Regenerer vignettes existantes (WP-CLI)
    wp media regenerate --yes
    

    4.3 Optimisation frontend avancee

    A. Minification et concatenation

    Plugin recommande: Autoptimize

    Configuration optimale:

    // wp-config.php
    define('AUTOPTIMIZEENABLED', true);
    
    // Via filtre
    addfilter('autoptimizefilterjsexclude', function($exclude) {
        return $exclude . ', jquery.js, analytics.js';
    });
    

    Alternative: Asset CleanUp (controle granulaire par page)

    B. Eliminer render-blocking

    Defer JavaScript:

    // functions.php
    function deferparsingjs($url) {
        if (isadmin()) return $url;
        if (strpos($url, '.js') === false) return $url;
        if (strpos($url, 'jquery.js')) return $url; // Exclure jQuery
        return strreplace(' src', ' defer src', $url);
    }
    addfilter('scriptloadertag', 'deferparsingjs', 10);
    

    Preload critical resources:

    // functions.php
    function preloadcriticalassets() {
        echo '';
        echo '';
        echo '';
    }
    addaction('wphead', 'preloadcriticalassets', 1);
    

    C. Critical CSS

    Plugin: WP Rocket (premium) – Generation automatique

    Manuel (technique avancee):

    Installer criticalcss

    npm install -g criticalcss

    Generer CSS critique

    criticalcss https://example.com > critical.css

    Inline critical CSS:

    // functions.php
    function inlinecriticalcss() {
        echo '';
    }
    addaction('wphead', 'inlinecriticalcss', 1);
    
    // Charger CSS complet async
    function asyncloadcss() {
        echo '';
    }
    addaction('wphead', 'asyncloadcss', 2);
    

    D. Speculation Rules API (2025)

    WordPress Core supporte desormais Speculation Rules pour pre-chargement instantane:

    // functions.php - Activer prefetch liens
    function addspeculationrules() {
        ?>
        
        action('wpfooter', 'addspeculationrules');
    

    Resultat: Chargement quasi-instantane pages suivantes

    4.4 CDN et optimisations edge

    A. Configuration Cloudflare (recommande)

    Plan Pro minimum pour:

  • Polish (optimisation images automatique)
  • Mirage (lazy loading intelligent)
  • Argo Smart Routing (acceleration -30% TTFB)
  • Workers (edge computing)
  • Settings optimaux Cloudflare:

    Speed > Optimization:
    
  • Auto Minify: ON (HTML, CSS, JS)
  • Brotli: ON
  • Early Hints: ON
  • Rocket Loader: OFF (conflit WordPress)
  • HTTP/3 (with QUIC): ON
  • Caching:
  • Caching Level: Standard
  • Browser Cache TTL: Respect Existing Headers
  • Always Online: ON
  • Page Rules (example.com/
    ):
  • Cache Level: Cache Everything
  • Edge Cache TTL: 1 month
  • Browser Cache TTL: 4 hours
  • Plugin WordPress: Cloudflare (officiel) – Purge cache automatique

    B. Cloudflare Workers pour optimisations edge

    Worker HTML minification:

    addEventListener('fetch', event => {
      event.respondWith(handleRequest(event.request))
    })
    
    async function handleRequest(request) {
      const response = await fetch(request)
      const contentType = response.headers.get('content-type')
    
      if (contentType && contentType.includes('text/html')) {
        let html = await response.text()
    
        // Minification basique
        html = html.replace(/s+/g, ' ')
                   .replace(/>s+<')
    
        return new Response(html, {
          headers: response.headers,
          status: response.status
        })
      }
    
      return response
    }
    

    C. Configuration headers cache

    Nginx configuration:

    Cache statique agressif

    location ~ .(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ { expires 1y; addheader Cache-Control "public, immutable"; accesslog off; }

    HTML - cache court avec revalidation

    location ~
    .html$ { expires 1h; add
    header Cache-Control "public, must-revalidate"; }

    WordPress headers cache:

    // functions.php
    function setcacheheaders() {
        if (!isuserloggedin() && !isadmin()) {
            header('Cache-Control: public, max-age=3600, must-revalidate');
            header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
        }
    }
    addaction('sendheaders', 'setcacheheaders');
    

    4.5 Base de donnees haute performance

    A. Configuration MariaDB 10.11 optimisee

    my.cnf pour serveur 8GB RAM:

    [mysqld]
    

    Performance schema

    performanceschema = ON

    InnoDB settings

    innodb
    bufferpoolsize = 4G # 50% RAM disponible innodblogfilesize = 512M innodbflushlogattrxcommit = 2 # Performance (risque perte 1s data) innodbflushmethod = ODIRECT innodbfilepertable = 1

    Query cache (deprecated MySQL 8+, ok MariaDB)

    querycachetype = 1 querycachesize = 256M querycachelimit = 2M

    Connections

    maxconnections = 200 threadcachesize = 50

    Temp tables

    tmp
    tablesize = 256M maxheaptablesize = 256M

    Logs

    slowquerylog = 1 slowquerylogfile = /var/log/mysql/slow-query.log longquerytime = 2 logqueriesnotusingindexes = 1

    Character set

    character
    setserver = utf8mb4 collationserver = utf8mb4unicodeci

    B. Optimisation tables WordPress

    Nettoyage regulier:

    -- Supprimer revisions anciennes (garder 5 dernieres)
    DELETE FROM wpposts
    WHERE posttype = 'revision'
    AND ID NOT IN (
        SELECT ID FROM (
            SELECT ID FROM wpposts
            WHERE posttype = 'revision'
            ORDER BY postmodified DESC
            LIMIT 5
        ) tmp
    );
    
    -- Vider corbeille
    DELETE FROM wpposts WHERE poststatus = 'trash';
    
    -- Supprimer transients expires
    DELETE FROM wpoptions WHERE optionname LIKE 'transient%';
    
    -- Optimiser tables
    OPTIMIZE TABLE wpposts, wppostmeta, wpoptions, wpcomments, wpcommentmeta;
    

    Automatisation via WP-CLI:

    Script cron hebdomadaire

    #!/bin/bash wp transient delete --all --path=/var/www/example.com/htdocs --allow-root wp post delete $(wp post list --poststatus=trash --format=ids --path=/var/www/example.com/htdocs --allow-root) --force --allow-root wp db optimize --path=/var/www/example.com/htdocs --allow-root

    C. Index personalises haute performance

    Requetes lentes communes WordPress:

    -- Trouver requetes lentes
    SELECT  FROM mysql.slowlog ORDER BY querytime DESC LIMIT 10;
    
    -- Index metakey pour postmeta (requetes custom fields)
    CREATE INDEX metakeyvalue ON wppostmeta(metakey, metavalue(20));
    
    -- Index recherche commentaires
    CREATE INDEX commentapprovedpostid ON wpcomments(commentapproved, commentpostID);
    

    Plugin recommande: Query Monitor - Identification requetes lentes temps reel

    D. Read replicas et load balancing (tres haute volumetrie)

    Configuration HyperDB (multi-DB):

    // db-config.php
    $wpdb->adddatabase(array(
        'host'     => '192.168.1.10', // Master
        'user'     => 'wpuser',
        'password' => 'password',
        'name'     => 'wordpressdb',
        'write'    => 1,
        'read'     => 1,
    ));
    
    $wpdb->adddatabase(array(
        'host'     => '192.168.1.11', // Replica 1 (read-only)
        'user'     => 'wpuser',
        'password' => 'password',
        'name'     => 'wordpressdb',
        'write'    => 0,
        'read'     => 1,
    ));
    
    $wpdb->adddatabase(array(
        'host'     => '192.168.1.12', // Replica 2 (read-only)
        'user'     => 'wpuser',
        'password' => 'password',
        'name'     => 'wordpressdb',
        'write'    => 0,
        'read'     => 1,
    ));
    

    4.6 Monitoring et observabilite

    A. Monitoring serveur avec Netdata

    Installation:

    Installation one-liner

    bash <(curl -Ss https://get.netdata.cloud/kickstart.sh)

    Acces: http://votre-ip:19999

    Metriques surveillees:

  • CPU, RAM, I/O disque temps reel
  • Nginx connections et requests/s
  • PHP-FPM pools et memoire
  • MySQL queries et slow queries
  • Redis memory et ops/s
  • B. Application Performance Monitoring (APM)

    New Relic (recommande):

    Installer agent PHP

    wget -O - https://download.newrelic.com/548C16BF.gpg | apt-key add - echo 'deb http://apt.newrelic.com/debian/ newrelic non-free' > /etc/apt/sources.list.d/newrelic.list apt update apt install newrelic-php5

    Configuration

    newrelic-install install

    Redemarrer PHP-FPM

    systemctl restart php8.3-fpm

    Plugin WordPress: New Relic Reporting

    C. Monitoring WordPress avec Query Monitor

    Installation

    wp plugin install query-monitor --activate --allow-root

    Fonctionnalites:

  • Requetes base de donnees + temps execution
  • Hooks WordPress executes
  • Scripts et styles charges
  • Erreurs PHP et notices
  • HTTP API calls
  • D. Uptime monitoring externe

    Services recommandes:

  • UptimeRobot (gratuit) - Check toutes les 5min
  • Pingdom (premium) - Monitoring multi-regions
  • Hetrix Tools (freemium) - Monitoring serveur + blacklist
  • Configuration webhook alertes:

    Script alerte Slack

    #!/bin/bash SLACK
    WEBHOOK="https://hooks.slack.com/services/YOUR/WEBHOOK/URL" MESSAGE="ALERT: Site example.com DOWN!" curl -X POST -H 'Content-type: application/json' --data "{"text":"$MESSAGE"}" $SLACKWEBHOOK

    E. Logs centralises

    Configuration rsyslog vers service central:

    /etc/rsyslog.d/50-wordpress.conf

    Envoyer logs Nginx/PHP vers serveur centralise

    . @logs.example.com:514

    Alternative cloud: Logtail, Papertrail, Datadog Logs

    Projet pratique Phase 4

    Optimisation site haute performance complete:

  • Auditer site existant (GTmetrix, PageSpeed Insights, WebPageTest)
  • Implementer formats images modernes (AVIF + WebP)
  • Configurer CDN Cloudflare avec settings optimaux
  • Implementer critical CSS et defer JS
  • Activer Speculation Rules API
  • Optimiser configuration MariaDB selon RAM disponible
  • Creer index base de donnees personnalises
  • Installer et configurer monitoring (Netdata + Query Monitor)
  • Effectuer tests charge avant/apres (k6, Apache Bench)
  • Documenter gains performance (screenshots audits)
  • Objectifs mesurables:

  • PageSpeed Score > 90 (mobile et desktop)
  • TTFB < 200ms
  • LCP < 2s
  • 1000+ req/s soutenus
  • Capacite 500+ utilisateurs concurrents
  • Ressources:

  • Ultimate WordPress Performance Guide 2025 - WP Engine
  • WordPress Performance Analysis - WordPress.com
  • Best Caching Setups VPS 2025 - Fussion Host
  • ---

    Phase 5 : Workflows Assistes par IA

    Objectifs

  • Integrer Claude.ai et ChatGPT dans workflow developpement
  • Accelerer developpement plugins/themes avec IA
  • Automatiser taches repetitives avec IA
  • Debugger et optimiser code avec assistance IA
  • Competences techniques

    5.1 Claude Code pour developpement WordPress

    A. Configuration environnement local + Claude Code

    Contexte 2025: Claude Code est devenu l'outil de reference pour le developpement WordPress assiste par IA grace a son contexte 200K tokens permettant d'analyser des codebases completes.

    Setup recommande:

  • Local by Flywheel ou Laravel Herd pour environnement local
  • Claude Pro (20$/mois) ou Claude Max (100$/mois) - Usage illimite recommande
  • VS Code avec extension Claude (si disponible)
  • Workflow "Vibe Coding" (methode 2025):

  • Wireframe ASCII - Visualiser sans coder
  • Requirements - Definir specifications
  • Rules - Etablir contraintes techniques
  • Execution - Laisser Claude generer code
  • Exemple session Claude Code:

    /wordpress-local
    
    [Claude analyse automatiquement votre environnement WordPress local]
    
    Vous: Je veux creer un plugin de gestion d'inventaire pour WooCommerce
    avec les fonctionnalites suivantes:
    
  • Alertes stock bas
  • Import CSV produits
  • Dashboard avec graphiques
  • API REST pour integration tierce
  • Utilise:
  • WordPress Coding Standards
  • React pour dashboard
  • Chart.js pour graphiques
  • WP-CLI pour commandes
  • Claude: [Genere architecture complete + code en 15-20 minutes]

    Source: How I Vibe Code WordPress Plugin in 50min - Nathan Onn

    B. Custom instructions pour Claude (contexte WordPress)

    Fichier .claude-instructions (racine projet):

    WordPress Development Context

    Environment

  • WordPress Version: 6.7+
  • PHP Version: 8.3
  • Database: MariaDB 10.11
  • Server: Nginx + PHP-FPM
  • Coding Standards

  • Follow WordPress Coding Standards (WPCS)
  • Use WordPress functions over native PHP when possible
  • Sanitize inputs, escape outputs
  • Use prepared statements for database queries
  • Add nonce verification for forms
  • Use wpenqueuescript/style for assets
  • Naming Conventions

  • Plugin prefix: yawc
  • Text domain: your-awesome-wordpress-course
  • Hook prefix: yawc
  • Security Requirements

  • Validate and sanitize all inputs
  • Escape all outputs
  • Use nonces for form submissions
  • Check user capabilities
  • Prepare database queries
  • Performance

  • Minimize database queries
  • Use transients for caching
  • Enqueue scripts in footer when possible
  • Conditional loading (only load when needed)
  • Preferred Patterns

  • Object-oriented for plugins
  • Singleton pattern for main plugin class
  • Action/Filter hooks over direct function calls
  • WP-CLI commands for admin tasks
  • C. Prompts efficaces pour developpement WordPress

    Generation plugin complet:

    Cree un plugin WordPress "Advanced Contact Form" avec:
    
    Architecture:
    
  • Namespace: AdvancedContactForm
  • Classe principale singleton
  • Separation concerns (Admin, Frontend, API)
  • Fonctionnalites:
  • Shortcode [acfform]
  • Gutenberg block
  • Validation AJAX
  • Stockage submissions en CPT
  • Export CSV admin
  • API REST endpoint
  • Hooks pour extensions
  • Requirements techniques:
  • WordPress 6.4+
  • PHP 8.2+
  • Coding Standards WordPress
  • Inline documentation PHPDoc
  • Internationalisation complete
  • Uninstall cleanup
  • Genere structure complete avec tous fichiers.

    Debugging assistance:

    J'ai cette erreur WordPress:
    
    [Error log content]
    
    Context:
    
  • Plugin: [nom]
  • Fonction: [fonction]
  • Action declenchante: [action]
  • Analyse l'erreur, identifie la cause racine et propose solution + code corrige.

    Optimisation performance:

    Analyse cette fonction WordPress et optimise-la pour performance:
    
    [Code a optimiser]
    
    Focus sur:
    
  • Reduction requetes DB
  • Utilisation caching
  • Optimisation boucles
  • N+1 queries
  • Fournis version optimisee + explication changements.

    5.2 ChatGPT pour taches rapides et repetitives

    Comparaison ChatGPT vs Claude (WordPress 2025):

    Claude Pro:

  • Architecture et planification
  • Analyse codebase large (200K tokens)
  • Debugging complexe
  • Refactoring
  • ChatGPT Pro:

  • Code generation rapide
  • Taches repetitives
  • Snippets code
  • Documentation
  • Source: ChatGPT Pro vs Claude Pro WordPress Development - Varun Dubey

    Approche hybride recommandee (2025):

    Planning/Architecture → Claude Pro
    Implementation rapide → ChatGPT Pro + GitHub Copilot
    Debugging complexe → Claude Code
    Documentation → ChatGPT
    

    B. ChatGPT pour generation code snippets

    Prompt template efficace:

    Cree un snippet WordPress pour [fonctionnalite]
    
    Contraintes:
    
  • Compatible WordPress 6.4+
  • Suit WordPress Coding Standards
  • Inclut sanitization/validation
  • Ajoute comments inline
  • Gere erreurs
  • Format: Code pret a copier-coller dans functions.php ou plugin

    Exemples use cases:

    Custom post type:

    Cree un CPT "Portfolio" avec:
    
  • Taxonomies: Type (hierarchique), Tags (non-hierarchique)
  • Supports: title, editor, thumbnail, excerpt
  • Archive publique
  • REST API enabled
  • Icone dashicons-portfolio
  • Rewrite slug: /projets/
  • Custom REST endpoint:

    Cree endpoint REST WordPress:
    
    GET /wp-json/myapi/v1/stats
    
    Response:
    {
      "totalposts": int,
      "totalusers": int,
      "populartags": array
    }
    
    Securite: Accessible seulement admin
    Cache: 1 heure via transients
    

    C. GitHub Copilot integration

    Installation VS Code:

    Extension GitHub Copilot

    code --install-extension GitHub.copilot

    Settings optimaux WordPress (settings.json):

    {
      "github.copilot.enable": {
        "": true,
        "yaml": true,
        "plaintext": false,
        "markdown": true,
        "php": true
      },
      "github.copilot.advanced": {
        "language": {
          "php": {
            "completions": {
              "wordpress": true
            }
          }
        }
      }
    }
    

    Workflow recommande:

    Developpement general → GitHub Copilot (inline suggestions)
    Questions complexes → Claude Code (browser tab ouvert)
    Snippets rapides → ChatGPT (second ecran)
    

    Source: 7 Smart Ways to Use AI in WordPress - Kinsta

    5.3 Automatisation workflows avec IA

    A. Uncanny Automator + OpenAI/Claude

    Plugin: Uncanny Automator Pro (integration OpenAI et Anthropic Claude)

    Use cases automatisation:

    1. Moderation commentaires intelligente:

    Trigger: Nouveau commentaire soumis
    Action: Envoyer a Claude API
    Prompt: "Analyse ce commentaire et determine s'il est:
    
  • Spam
  • Inapproprie
  • Legitime
  • Commentaire: {{comment
    content}} Auteur: {{commentauthor}}" Condition:
  • Si "spam" ou "inapproprie" → Marquer spam
  • Si "legitime" → Approuver
  • 2. Generation descriptions produits WooCommerce:

    Trigger: Nouveau produit publie sans description
    Action: Envoyer a ChatGPT API
    Prompt: "Genere description produit SEO-optimisee (150-200 mots) pour:
    
    Nom: {{productname}}
    Categorie: {{productcategory}}
    Attributs: {{productattributes}}
    
    Ton: Professionnel, persuasif
    Focus: Benefices client"
    
    Action: Mettre a jour postcontent du produit
    

    3. Reponses emails personnalisees:

    Trigger: Soumission formulaire contact
    Action: Envoyer a Claude API avec historique client
    Prompt: "Genere reponse personnalisee basee sur:
    
    Message client: {{formmessage}}
    Historique: {{userpurchasehistory}}
    Categorie question: {{formcategory}}
    
    Ton: Amical, professionnel
    Longueur: 100-150 mots"
    
    Action: Envoyer email + ajouter tag CRM
    

    B. WP-CLI + IA pour maintenance automatisee

    Script analyse securite avec Claude API:

    #!/bin/bash
    

    audit-security-ai.sh

    SITE
    PATH="/var/www/example.com/htdocs" CLAUDEAPIKEY="your-api-key"

    Generer rapport WPScan

    wpscan --url https://example.com --format json > /tmp/wpscan-report.json

    Envoyer a Claude pour analyse

    REPORT=$(cat /tmp/wpscan-report.json) RESPONSE=$(curl -s https://api.anthropic.com/v1/messages -H "x-api-key: $CLAUDEAPIKEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d "{ "model": "claude-3-5-sonnet-20241022", "maxtokens": 2048, "messages": [{ "role": "user", "content": "Analyse ce rapport WPScan et fournis recommandations priorisees pour securiser le site. Focus sur vulnerabilites critiques et actions immediates.nnRapport:n$REPORT" }] }")

    Extraire recommandations et envoyer par email

    echo "$RESPONSE" | jq -r '.content[0].text' | mail -s "Audit Securite IA - $(date)" admin@example.com

    C. Generation contenu avec IA + publication automatique

    Plugin: AI Engine + WP Cron

    Workflow blog automatise:

    // functions.php - Generer article hebdomadaire
    
    addaction('aiweeklypostgeneration', 'generateaiweeklypost');
    
    function generateaiweeklypost() {
        // Topics pre-definis
        $topics = getoption('aiblogtopics', [
            'WordPress performance optimization',
            'Security best practices',
            'Plugin development tutorials'
        ]);
    
        $randomtopic = $topics[arrayrand($topics)];
    
        // API OpenAI
        $prompt = "Ecris article blog 800-1000 mots sur: $randomtopic
    
        Structure:
        - Introduction accrocheuse
        - 3-4 sections avec sous-titres H2
        - Exemples concrets
        - Conclusion avec CTA
    
        Ton: Expert mais accessible
        SEO: Inclure mot-cle naturellement 5-7 fois";
    
        $response = openaicompletion([
            'model' => 'gpt-4-turbo',
            'messages' => [
                ['role' => 'system', 'content' => 'Tu es expert WordPress et redacteur technique.'],
                ['role' => 'user', 'content' => $prompt]
            ],
            'maxtokens' => 2000
        ]);
    
        $content = $response['choices'][0]['message']['content'];
    
        // Creer brouillon
        $postid = wpinsertpost([
            'posttitle'   => "AI Generated: $randomtopic",
            'postcontent' => $content,
            'poststatus'  => 'draft',
            'postauthor'  => 1,
            'postcategory'=> [getcatID('AI Content')]
        ]);
    
        // Notifier admin pour review
        wpmail(
            getoption('adminemail'),
            'Nouveau brouillon IA genere',
            "Article genere sur: $randomtopicnReview: " . geteditpostlink($postid)
        );
    }
    
    // Scheduler hebdomadaire
    if (!wpnextscheduled('aiweeklypostgeneration')) {
        wpscheduleevent(time(), 'weekly', 'aiweeklypostgeneration');
    }
    

    5.4 Cas d'usage avances IA WordPress

    A. Refactoring legacy code avec Claude

    Prompt structure:

    Refactore ce code WordPress legacy vers modern standards:
    
    [Ancien code]
    
    Requirements:
    
  • PHP 8.3 compatible
  • Object-oriented
  • WordPress Coding Standards
  • Type hints strict
  • Error handling robuste
  • PHPDoc complete
  • Backward compatibility optionnelle
  • Explique changements majeurs et rationale.

    B. Generation tests unitaires automatique

    Prompt ChatGPT:

    Genere tests PHPUnit pour cette classe WordPress:
    
    [Code classe]
    
    Coverage requise:
    
  • Tous methodes publiques
  • Edge cases
  • Error handling
  • WordPress integration (use BrainMonkey)
  • Format: PHPUnit 10+ compatible

    C. Optimisation requetes base de donnees

    Prompt Claude:

    Analyse ces logs Query Monitor et optimise les requetes problematiques:
    
    [Query logs]
    
    Focus:
    
  • Eliminer N+1 queries
  • Ajouter index appropries
  • Utiliser WPQuery efficacement
  • Implementer object caching
  • Fournis:
  • SQL index a creer
  • Code optimise
  • Impact performance estime
  • D. Creation documentation automatique

    Script avec ChatGPT API:

    #!/bin/bash
    

    generate-docs.sh

    Extraire tous fichiers PHP plugin

    PLUGIN
    DIR="/var/www/example.com/htdocs/wp-content/plugins/mon-plugin" PHPFILES=$(find "$PLUGINDIR" -name ".php")

    Concatener code source

    CODE="" for file in $PHPFILES; do CODE+="=== $file ===n" CODE+=$(cat "$file") CODE+="nn" done

    Generer documentation via ChatGPT

    curl -s https://api.openai.com/v1/chat/completions -H "Authorization: Bearer $OPENAI
    APIKEY" -H "Content-Type: application/json" -d "{ "model": "gpt-4-turbo", "messages": [{ "role": "user", "content": "Genere documentation technique complete pour ce plugin WordPress. Inclus: architecture, hooks disponibles, exemples utilisation, API reference.nnCode:n$CODE" }], "maxtokens": 4000 }" | jq -r '.choices[0].message.content' > "$PLUGINDIR/DOCUMENTATION.md" echo "Documentation generee: $PLUGINDIR/DOCUMENTATION.md"

    Projet pratique Phase 5

    Integration IA complete dans workflow:

  • Configurer Claude Pro + ChatGPT Pro
  • Installer GitHub Copilot dans VS Code
  • Creer plugin WordPress complet avec assistance Claude (30-60min)
  • Generer tests unitaires automatiques avec ChatGPT
  • Implementer automatisation Uncanny Automator + OpenAI
  • Creer script maintenance assiste IA (audit securite, optimization)
  • Generer documentation automatique projet
  • Mesurer gains productivite (temps avant/apres IA)
  • Livrable:

  • Plugin fonctionnel genere avec IA
  • Documentation complete auto-generee
  • Scripts automatisation
  • Rapport gains productivite (estimation 40-60% reduction temps developpement)
  • Ressources:

  • Building WordPress AI Workflow - JPTWeb
  • WordPress AI Plugins Guide 2025 - Wordable
  • AI Workflow Automation WordPress - Bit Flows
  • ---

    Projet Final : Deploiement Infrastructure Production Complete

    Objectif

    Deployer une infrastructure WordPress production complete integrant toutes competences acquises.

    Specifications techniques

    Infrastructure:

  • VPS Debian 12 (8GB RAM, 4vCPU, NVMe)
  • WordOps stack optimise
  • Multi-environnements (staging + production)
  • Monitoring complet
  • Performance:

  • Cache Nginx FastCGI + Redis Object Cache
  • CDN Cloudflare configure
  • Optimisations images (AVIF/WebP)
  • Score PageSpeed > 90
  • Securite:

  • Hardening complet wp-config.php
  • WAF niveau application
  • 2FA tous administrateurs
  • Headers securite HTTP
  • SSL A+ rating
  • CI/CD:

  • Repository Git structure
  • GitHub Actions pipelines (staging + production)
  • Tests automatises (PHPUnit, PHPCS, PHPStan)
  • Deploiements automatiques
  • Rollback automatique si echec
  • Monitoring:

  • Netdata metriques serveur
  • New Relic APM
  • Query Monitor WordPress
  • Uptime monitoring externe
  • Alertes Slack/Email
  • IA Integration:

  • Workflows assistes Claude/ChatGPT
  • Automatisations Uncanny Automator
  • Scripts maintenance IA
  • Livrables

  • Documentation technique complete:
  • - Architecture infrastructure
    - Procedures deploiement
    - Runbooks incidents
    - Guide maintenance

  • Repository Git:
  • - Code source organise
    - Workflows CI/CD fonctionnels
    - Tests automatises
    - Documentation inline

  • Dashboards monitoring:
  • - Screenshots Netdata
    - Rapports New Relic
    - Audits performance (GTmetrix, PageSpeed)

  • Rapport performance:
  • - Benchmarks charge (k6, Apache Bench)
    - Metriques Core Web Vitals
    - Capacite utilisateurs concurrents
    - TTFB, LCP, FID, CLS

  • Audit securite:
  • - Rapport WPScan
    - Scan headers (SecurityHeaders.com)
    - SSL Labs rating
    - Procedures incident response

    Criteres evaluation

  • Performance: TTFB < 200ms, PageSpeed > 90, 500+ utilisateurs concurrents
  • Securite: Zero vulnerabilites critiques, A+ SSL, tous headers securite
  • CI/CD: Deploiement automatique < 5min, tests passes 100%
  • Monitoring: Alertes fonctionnelles, metriques collectees
  • Documentation: Complete, claire, reproductible
  • ---

    Ressources Complementaires

    Documentation officielle

  • WordPress Developer Handbook
  • WordPress Advanced Administration
  • WordOps Documentation
  • Nginx Documentation
  • MariaDB Knowledge Base
  • Outils performance

  • GTmetrix
  • PageSpeed Insights
  • WebPageTest
  • k6 Load Testing
  • Outils securite

  • WPScan
  • Sucuri SiteCheck
  • SecurityHeaders.com
  • SSL Labs
  • Communautes

  • WordPress StackExchange
  • WordOps Community Forum
  • r/WordPress
  • WP Tavern
  • Formation continue

  • WordPress TV
  • Smashing Magazine WordPress
  • CSS-Tricks WordPress
  • ---

    Conclusion

    Ce parcours intermediaire vous a equipe des competences essentielles pour gerer des infrastructures WordPress production haute performance. Vous maitrisez desormais:

  • Le deploiement et l'optimisation de stacks VPS avec WordOps
  • L'implementation de caches multi-couches (Nginx FastCGI + Redis)
  • Les techniques de hardening securite 2025 (face a 7966+ vulnerabilites annuelles)
  • L'automatisation complete CI/CD avec GitHub Actions
  • L'optimisation performance grande echelle (Core Web Vitals, CDN, database)
  • L'integration workflows IA pour accelerer productivite 40-60%
  • Prochaines etapes: Parcours Avance - Architecture haute disponibilite, Kubernetes WordPress, scaling horizontal, disaster recovery.

    Duree moyenne realisation: 12-16 semaines a raison de 15-20h/semaine.

    Bon courage dans votre apprentissage!

    ---

    Version: 1.0
    Derniere mise a jour: Decembre 2025
    Auteur: You Are Welcome Community
    License:
    * CC BY-SA 4.0

    Sources

    Ce parcours s'appuie sur des donnees verifiees et des guides techniques publies en 2025:

    Performance WordPress

  • 15 Proven WordPress Performance Optimization Tips That Actually Work in 2025
  • Ultimate WordPress Performance Optimization Guide - WP Engine
  • WordPress Performance Analysis - WordPress.com
  • Best Caching Setups for WordPress VPS in 2025
  • CI/CD et GitHub Actions

  • Continuous Deployments for WordPress Using GitHub Actions - CSS-Tricks
  • GitHub Actions for WordPress - Axioned Handbook
  • rtCamp WordPress Deploy Action
  • Building a CI/CD Workflow - Pressidium
  • WordOps et VPS

  • WordOps: Complete Review and Hands-On Guide - BigMike.help
  • Installing WordOps on VPS: Ultimate Guide - Linux Nest
  • WordOps Official Documentation
  • Securite WordPress

  • WordPress Security Hardening Guide 2025 - Security Ninja
  • WordPress Security Best Practices 2025 - WP Umbrella
  • Hardening WordPress - WordPress Developer Handbook
  • Q3 2025 Most Exploited WordPress Vulnerabilities - Patchstack
  • Cache et Performance

  • Redis Object Caching for WordPress 2025 - Boosted Host
  • Configure Redis Object Cache - Boosted Host
  • Configuring Nginx FastCGI Cache - DoHost
  • How To Use NGINX FastCGI Cache - RunCloud
  • IA et WordPress

  • How I Vibe Code WordPress Plugin with Claude Code - Nathan Onn
  • Building WordPress AI Dev Workflow with Claude Code - JPTWeb
  • ChatGPT Pro vs Claude Pro WordPress Development - Varun Dubey
  • 7 Smart Ways to Use AI in WordPress - Kinsta
  • WordPress AI Plugins Guide 2025 - Wordable
  • AI Workflow Automation in WordPress - Bit Flows