Deploy WordPress con Git e Staging

Modifiche via FTP direttamente in produzione? Nel 2026 non è più accettabile. Ecco come implementare un workflow Git professionale per WordPress.

Il Problema del “Cowboy Coding”

# Scenario disastroso (troppo comune):

1. Cliente chiede modifica urgente
2. Sviluppatore si collega via FTP
3. Modifica file direttamente in produzione  
4. Qualcosa si rompe
5. Nessun backup delle modifiche precedenti
6. Panico

# Conseguenze:
- Downtime non tracciato
- Impossibile fare rollback
- Modifiche perse o sovrascritte
- Debug impossibile
- Nessuna history delle modifiche

1. Setup Repository Git

Struttura Consigliata

# .gitignore per WordPress

# Core WordPress (no commit)
/wp-admin/
/wp-includes/
/wp-*.php
/index.php
/license.txt
/readme.html
/xmlrpc.php

# Contenuti utente (no commit)
/wp-content/uploads/
/wp-content/upgrade/
/wp-content/cache/
/wp-content/backup-db/

# Plugin di terze parti (no commit)
/wp-content/plugins/*
!/wp-content/plugins/mio-plugin-custom/

# Config sensibili
wp-config.php
.env
*.log

# SÌ commit: solo tema custom e plugin custom
!/wp-content/themes/mio-tema/

Inizializza Repository

# Nella root locale
cd ~/Sites/mio-progetto

# Init Git
git init
git add .
git commit -m "Initial commit: tema custom v1.0"

# Collega a remote (GitHub/GitLab/Bitbucket)
git remote add origin [email protected]:team/progetto.git
git push -u origin main

2. Ambienti: Local → Staging → Produzione

┌──────────────┐    ┌──────────────┐    ┌──────────────┐
│   LOCAL      │───▶│   STAGING    │───▶│  PRODUCTION  │
│  develop     │    │   staging    │    │    main      │
│  localhost   │    │  staging.xx  │    │   sito.it    │
└──────────────┘    └──────────────┘    └──────────────┘
     ▲                    ▲                    ▲
     │                    │                    │
  Sviluppo            Test QA              Approvato
  Libero              Cliente              Solo merge

Git Flow Semplificato

# Branch strategy:
main        → produzione (protetto, solo merge)
staging     → ambiente test cliente
develop     → sviluppo attivo
feature/*   → nuove funzionalità

# Workflow quotidiano:
git checkout develop
git pull origin develop
git checkout -b feature/nuova-sezione

# ... sviluppo ...

git add .
git commit -m "Aggiunta sezione servizi"
git push origin feature/nuova-sezione

# Pull Request: feature/* → develop
# Dopo review: develop → staging (per test cliente)
# Dopo approvazione: staging → main (deploy prod)

3. Deploy Automatico con Git Hooks

Setup Server (post-receive hook)

# Sul server, crea bare repository
ssh user@server
mkdir -p /var/repo/sito.git
cd /var/repo/sito.git
git init --bare

# Crea hook post-receive
nano hooks/post-receive
#!/bin/bash
# hooks/post-receive

TARGET="/var/www/sito.it/wp-content/themes/mio-tema"
GIT_DIR="/var/repo/sito.git"
BRANCH="main"

while read oldrev newrev ref
do
    if [[ $ref = refs/heads/$BRANCH ]]; then
        echo "Deploying $BRANCH to $TARGET..."
        git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH
        
        # Clear cache dopo deploy
        wp cache flush --path=/var/www/sito.it
        
        echo "Deploy completato!"
    fi
done
# Rendi eseguibile
chmod +x hooks/post-receive

# In locale, aggiungi remote di deploy
git remote add production ssh://user@server/var/repo/sito.git

# Deploy = push
git push production main

4. Alternative: Deploy con GitHub Actions

# .github/workflows/deploy.yml
name: Deploy to Production

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Deploy via SSH
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_KEY }}
          script: |
            cd /var/www/sito.it
            git pull origin main
            wp cache flush

5. Sincronizzazione Database

Il database è la parte più delicata. Due approcci:

A. Script WP-CLI per Sync

#!/bin/bash
# sync-staging.sh - Copia produzione → staging

PROD_HOST="[email protected]"
STAGING_PATH="/var/www/staging"

# Export DB da produzione
ssh $PROD_HOST "wp db export - --path=/var/www/sito" > prod-db.sql

# Import in staging
wp db import prod-db.sql --path=$STAGING_PATH

# Search-replace URL
wp search-replace 'https://sito.it' 'https://staging.sito.it' \
   --path=$STAGING_PATH --all-tables

# Pulisci
rm prod-db.sql

echo "Staging sincronizzato!"

B. Solo Contenuti Specifici

# Esporta solo post/pages da prod
wp export --post_type=post,page --stdout > content.xml

# Importa in staging  
wp import content.xml --authors=skip

6. Rollback Istantaneo

# Qualcosa è andato storto? Rollback in 30 secondi:

# Vedi ultimi commit
git log --oneline -10

# Rollback al commit precedente
git revert HEAD --no-edit
git push production main

# Oppure reset completo (più drastico)
git reset --hard HEAD~1
git push -f production main

# Rispetto a FTP:
# - FTP: "qual era il file prima? dove l'ho messo?"
# - Git: un comando, 30 secondi, garantito

7. Benefici del Workflow Git

✓ History completa di ogni modifica
✓ Rollback istantaneo
✓ Code review prima del deploy
✓ Ambiente staging per test cliente
✓ Collaborazione team senza conflitti
✓ Deploy automatico e ripetibile
✓ Nessun file "sovrascrittura_backup_v2_finale.php"
✓ CI/CD possibile (test automatici)

Vuoi professionalizzare il tuo workflow WordPress? Configuriamo Git, staging e deploy automatico per il tuo progetto. Contattaci per una consulenza DevOps.