# WP-CLI no CWP — Referência Completa de Comandos

**Servidor:** server.descomplicar.pt (176.9.3.158) | porta 9443
**PHP padrão:** `/opt/alt/php-fpm83/usr/bin/php`

---

## Formato Base

```bash
/opt/alt/php-fpm83/usr/bin/php /usr/local/bin/wp GRUPO SUBCOMANDO [FLAGS] --allow-root --path=/home/USER/public_html
```

---

## Core WordPress

```bash
wp core version                          # Versão actual
wp core update                           # Actualizar para latest
wp core update --version=6.4.3 --force   # Versão específica
wp core download                         # Descarregar sem instalar
wp core verify-checksums                 # Verificar integridade ficheiros
wp core install --url=... --title=... \
  --admin_user=admin --admin_email=...   # Instalar novo WordPress
wp core is-installed                     # Verificar se está instalado
wp core update-db                        # Actualizar base de dados após update
```

---

## Plugins

```bash
wp plugin list                            # Listar todos
wp plugin list --status=inactive          # Só inactivos
wp plugin list --update=available         # Com updates disponíveis
wp plugin install SLUG                    # Instalar
wp plugin install SLUG --activate         # Instalar e activar
wp plugin install SLUG --version=X.X      # Versão específica
wp plugin activate SLUG                   # Activar
wp plugin deactivate SLUG                 # Desactivar
wp plugin deactivate --all                # Desactivar todos (debug)
wp plugin delete SLUG                     # Remover ficheiros
wp plugin update SLUG                     # Actualizar plugin específico
wp plugin update --all                    # Actualizar todos
wp plugin update --all --dry-run          # Preview de updates
wp plugin verify-checksums SLUG           # Verificar integridade
wp plugin verify-checksums --all          # Verificar todos
wp plugin search TERMO                    # Pesquisar no repo WordPress.org
wp plugin get SLUG                        # Info detalhada
wp plugin path SLUG                       # Path do plugin no servidor
```

---

## Temas

```bash
wp theme list                             # Listar todos
wp theme install SLUG                     # Instalar
wp theme install SLUG --activate          # Instalar e activar
wp theme activate SLUG                    # Activar tema
wp theme update SLUG                      # Actualizar
wp theme update --all                     # Actualizar todos
wp theme delete SLUG                      # Remover
wp theme get SLUG                         # Info detalhada
wp theme is-active SLUG                   # Verificar se activo
```

---

## Base de Dados

```bash
wp db export /caminho/backup.sql          # Exportar
wp db export - | gzip > backup.sql.gz     # Exportar comprimido
wp db import backup.sql                   # Importar
wp db optimize                            # Optimizar tabelas
wp db repair                              # Reparar tabelas
wp db check                               # Verificar integridade
wp db size                                # Tamanho da BD
wp db tables                              # Listar tabelas
wp db prefix                              # Prefixo actual
wp db query "SQL;"                        # Query directa
wp db search "TERMO"                      # Pesquisar em toda a BD
wp db clean --tables=revision             # Limpar revisões
```

---

## Search-Replace (Migração)

```bash
# SEMPRE fazer dry-run primeiro
wp search-replace 'old.com' 'new.com' --dry-run

# Executar
wp search-replace 'https://old.com' 'https://new.com'

# Só numa tabela
wp search-replace 'old' 'new' wp_options wp_postmeta

# Com relatório detalhado
wp search-replace 'old' 'new' --report-changed-only

# Sem serialization (mais rápido, menos seguro)
wp search-replace 'old' 'new' --no-php

# Número de linhas por batch (para BDs grandes)
wp search-replace 'old' 'new' --precise

# Skip tabelas específicas
wp search-replace 'old' 'new' --skip-tables=wp_users
```

---

## Options WordPress

```bash
wp option get NOME                        # Ler option
wp option update NOME VALOR               # Actualizar (simples)
wp option patch update NOME SUBKEY VALOR  # Actualizar sub-key (serialized)
wp option pluck NOME SUBKEY               # Ler sub-key
wp option add NOME VALOR                  # Adicionar
wp option delete NOME                     # Apagar
wp option list                            # Listar todas
wp option list --search='rank*'           # Filtrar por nome
wp option list --autoload=yes             # Só com autoload
```

---

## Post Meta / User Meta / Term Meta

```bash
# Post Meta
wp post meta list POST_ID                 # Listar meta de um post
wp post meta get POST_ID META_KEY         # Ler valor
wp post meta update POST_ID META_KEY VAL  # Actualizar
wp post meta add POST_ID META_KEY VAL     # Adicionar
wp post meta delete POST_ID META_KEY      # Apagar

# Com formato JSON (para arrays/objects)
wp post meta update POST_ID META_KEY '["val1","val2"]' --format=json

# Term Meta
wp term meta list TERM_ID
wp term meta get TERM_ID META_KEY
wp term meta update TERM_ID META_KEY VAL

# User Meta
wp user meta list USER_ID
wp user meta get USER_ID META_KEY
wp user meta update USER_ID META_KEY VAL
```

---

## Posts e Conteúdo

```bash
wp post list                              # Listar posts
wp post list --post_type=page             # Só páginas
wp post list --post_status=draft          # Só rascunhos
wp post get POST_ID                       # Info completa
wp post create --post_type=post \
  --post_title="Título" \
  --post_status=publish                   # Criar post
wp post update POST_ID --post_title="..." # Actualizar
wp post delete POST_ID                    # Apagar (lixo)
wp post delete POST_ID --force            # Apagar definitivo
wp post generate --count=10               # Gerar posts de teste
```

---

## Utilizadores

```bash
wp user list                              # Listar todos
wp user list --role=administrator         # Filtrar por papel
wp user get USER_ID                       # Info utilizador
wp user get USERNAME --field=ID           # Obter ID por username
wp user create LOGIN EMAIL \
  --role=administrator \
  --user_pass=SENHA                       # Criar
wp user update USER_ID --user_pass=SENHA  # Alterar password
wp user update USER_ID --user_email=...   # Alterar email
wp user set-role USER_ID administrator    # Alterar papel
wp user delete USER_ID --reassign=1       # Apagar, transferindo conteúdo
wp user check-password USER_ID SENHA      # Verificar password
wp user reset-password USER_ID            # Reset password (envia email)
```

---

## Cache e Transientes

```bash
wp cache flush                            # Limpar object cache
wp cache get KEY [GROUP]                  # Ler cache
wp transient delete --all                 # Apagar todos transientes
wp transient delete NOME                  # Apagar transiente específico
wp transient get NOME                     # Ler transiente
wp rewrite flush                          # Regenerar rewrite rules
wp rewrite list                           # Listar rules actuais
```

---

## Cron

```bash
wp cron event list                        # Listar eventos agendados
wp cron event run HOOK_NAME               # Executar agora
wp cron event delete HOOK_NAME            # Apagar evento
wp cron event schedule HOOK cron now      # Agendar evento
wp cron schedule list                     # Ver schedules disponíveis
wp cron test                              # Testar se cron está funcional
```

---

## wp eval — Execução PHP

```bash
# Código PHP inline
wp eval 'echo PHP_VERSION."\n";' --allow-root --path=$PATH

# Ficheiro PHP
wp eval-file script.php --allow-root --path=$PATH

# Com parâmetros
wp eval 'global $wpdb; echo $wpdb->prefix;' --allow-root --path=$PATH

# Ver constantes WordPress
wp eval 'echo WP_CONTENT_DIR."\n"; echo ABSPATH;' --allow-root --path=$PATH

# Executar com utilizador específico
wp eval 'echo get_current_user_id();' --user=1 --allow-root --path=$PATH
```

---

## Multisite

```bash
wp site list                              # Listar sites
wp site create --slug=subdomain           # Criar site
wp site activate ID                       # Activar
wp site deactivate ID                     # Desactivar
wp site delete ID                         # Apagar

# Executar comando em todos os sites
wp site list --field=url | xargs -I {} wp --url={} plugin list --allow-root --path=$PATH
```

---

## WooCommerce CLI

```bash
wp wc product list                        # Listar produtos
wp wc product get ID                      # Produto específico
wp wc product create --name="Nome" \
  --regular_price="19.99"                 # Criar produto
wp wc product update ID --regular_price="29.99" # Actualizar
wp wc product delete ID                   # Apagar

wp wc order list                          # Listar encomendas
wp wc order get ID                        # Encomenda específica
wp wc order update ID --status=completed  # Mudar estado

wp wc customer list                       # Listar clientes
wp wc shipping_zone list                  # Zonas de entrega
```

---

## Segurança e Diagnóstico

```bash
# Verificar integridade completa
wp core verify-checksums --allow-root --path=$PATH
wp plugin verify-checksums --all --allow-root --path=$PATH

# Configuração PHP activa
wp eval 'echo PHP_VERSION."\n".php_ini_loaded_file()."\n";' --allow-root --path=$PATH
wp eval 'echo ini_get("memory_limit")."\n".ini_get("max_execution_time");' --allow-root --path=$PATH

# Ver configuração WordPress
wp option get siteurl --allow-root --path=$PATH
wp option get blogname --allow-root --path=$PATH
wp option get active_plugins --format=json --allow-root --path=$PATH

# Verificar se WP_DEBUG activo
wp eval 'echo WP_DEBUG ? "DEBUG ON" : "DEBUG OFF";' --allow-root --path=$PATH

# Listar ficheiros modificados recentemente (possível hack)
find /home/USER/public_html -name "*.php" -newer /home/USER/public_html/wp-config.php -not -path "*/wp-content/cache/*" 2>/dev/null | head -20
```

---

## Scripts de Manutenção

### Backup completo de um site

```bash
#!/bin/bash
PATH_WP="/home/USER/public_html"
BACKUP_DIR="/media/ealmeida/Externo/LocalBackups/WP"
DATE=$(date +%Y%m%d_%H%M)
SITE=$(basename $(dirname $PATH_WP))

mkdir -p "$BACKUP_DIR"

# Backup BD
/opt/alt/php-fpm83/usr/bin/php /usr/local/bin/wp db export \
    "$BACKUP_DIR/${SITE}_db_${DATE}.sql" \
    --allow-root --path=$PATH_WP

# Backup ficheiros
tar -czf "$BACKUP_DIR/${SITE}_files_${DATE}.tar.gz" \
    -C $(dirname $PATH_WP) public_html \
    --exclude="public_html/wp-content/cache"

echo "Backup completo: $BACKUP_DIR"
```

### Manutenção semanal (todos os sites)

```bash
#!/bin/bash
find /home -name wp-config.php -not -path "*/backup*" 2>/dev/null | while read config; do
    dir=$(dirname "$config")
    user=$(stat -c '%U' "$dir")

    # Detectar PHP do utilizador
    php_fpm=$(ps aux | grep "php-fpm: pool ${user}" | grep -v grep | head -1 | grep -o 'php-fpm[0-9][0-9]' | head -1)
    php_ver=${php_fpm:-php-fpm82}
    php_bin="/opt/alt/${php_ver}/usr/bin/php"

    echo "=== $user ($dir) — PHP $php_ver ==="

    $php_bin /usr/local/bin/wp core update --allow-root --path="$dir" 2>/dev/null
    $php_bin /usr/local/bin/wp plugin update --all --allow-root --path="$dir" 2>/dev/null
    $php_bin /usr/local/bin/wp theme update --all --allow-root --path="$dir" 2>/dev/null
    $php_bin /usr/local/bin/wp db optimize --allow-root --path="$dir" 2>/dev/null
    $php_bin /usr/local/bin/wp cache flush --allow-root --path="$dir" 2>/dev/null
done
```

---

## Flags Globais Úteis

| Flag | Descrição |
|------|-----------|
| `--allow-root` | Obrigatório no CWP (executa como root) |
| `--path=/home/USER/public_html` | Caminho da instalação WordPress |
| `--url=https://site.pt` | URL do site (importante em multisite) |
| `--user=1` | Executar como utilizador WordPress específico |
| `--format=json\|table\|csv\|ids` | Formato do output |
| `--fields=ID,name` | Campos a mostrar |
| `--debug` | Output de debug detalhado |
| `--quiet` | Sem output (para scripts) |
| `--dry-run` | Preview sem executar (onde disponível) |
| `--skip-plugins` | Não carregar plugins (troubleshooting) |
| `--skip-themes` | Não carregar temas |

---

*WP-CLI CWP — Referência Completa | Descomplicar® | v1.0.0 | 18-02-2026*
