# Rank Math WP-CLI — Referência Completa de Comandos

**Manual Hub:** `06-Operacoes/Documentacao/Manuais/Rank-Math-WP-CLI-Manual-Definitivo.md`

---

## Arquitectura de Dados

### Tabelas WordPress Standard

| Tabela | Dados Rank Math |
|--------|-----------------|
| `wp_postmeta` | SEO por post: título, descrição, robots, schema, keywords |
| `wp_termmeta` | SEO por taxonomia (categories, tags) |
| `wp_usermeta` | SEO de páginas author archive |
| `wp_options` | Configurações globais do plugin |

### Tabelas Custom Rank Math

| Tabela | Conteúdo |
|--------|---------|
| `wp_rank_math_redirections` | Regras de redirect (301, 302, 410, etc.) |
| `wp_rank_math_redirections_cache` | Cache das regras |
| `wp_rank_math_404_logs` | Log de 404s com contadores |
| `wp_rank_math_analytics_objects` | Analytics (PRO) |
| `wp_rank_math_analytics_ga` | Google Analytics (PRO) |
| `wp_rank_math_analytics_gsc` | Search Console (PRO) |

---

## Meta Keys Completas (wp_postmeta)

### SEO Básico

| Meta Key | Tipo | Exemplo |
|----------|------|---------|
| `rank_math_title` | string | `%title% %sep% %sitename%` |
| `rank_math_description` | string | Máx 160 chars |
| `rank_math_focus_keyword` | string CSV | `kw1,kw2,kw3` |
| `rank_math_pillar_content` | string | `on` / `off` |
| `rank_math_canonical_url` | string URL | `https://site.pt/url/` |
| `rank_math_seo_score` | int | 0-100 (calculado no editor) |

### Robots e Indexação

| Meta Key | Tipo | Valores |
|----------|------|---------|
| `rank_math_robots` | **array JSON** | `["noindex"]`, `["nofollow"]`, `["noindex","nofollow"]` |

```bash
# CORRECTO
wp post meta update ID rank_math_robots '["noindex"]' --format=json --allow-root

# ERRADO (string, não aplicará)
wp post meta update ID rank_math_robots "noindex" --allow-root
```

### Open Graph / Social

| Meta Key | Tipo | Notas |
|----------|------|-------|
| `rank_math_facebook_image` | string URL | Imagem OG |
| `rank_math_facebook_title` | string | Título Facebook |
| `rank_math_facebook_description` | string | Descrição Facebook |
| `rank_math_twitter_card_type` | string | `summary_large_image` |
| `rank_math_twitter_title` | string | |
| `rank_math_twitter_description` | string | |
| `rank_math_twitter_image` | string URL | |

### Schema

| Meta Key | Tipo | Notas |
|----------|------|-------|
| `rank_math_schema_Article` | serialized PHP array | `wp eval` obrigatório |
| `rank_math_schema_FAQPage` | serialized PHP array | |
| `rank_math_schema_HowTo` | serialized PHP array | |
| `rank_math_schema_Product` | serialized PHP array | WooCommerce |
| `rank_math_schema_Recipe` | serialized PHP array | |
| `rank_math_schema_Review` | serialized PHP array | |
| `rank_math_schema_Event` | serialized PHP array | |
| `rank_math_schema_LocalBusiness` | serialized PHP array | |
| `rank_math_schema_VideoObject` | serialized PHP array | |

### WooCommerce

| Meta Key | Tipo | Notas |
|----------|------|-------|
| `rank_math_primary_category` | string (Term ID) | `"15"` |
| `rank_math_schema_Product` | serialized PHP array | Produto WC |

---

## Options Globais (wp_options)

### Options Principais

| Option Name | Tipo | Conteúdo |
|-------------|------|---------|
| `rank-math-options-general` | serialized array | Config geral |
| `rank-math-options-titles` | serialized array | Títulos e meta por post-type |
| `rank-math-options-sitemap` | serialized array | Configuração sitemap |
| `rank_math_modules` | serialized array | Módulos activos/inactivos |
| `rank_math_schema_types` | serialized array | Tipos schema habilitados |

### Sub-keys rank-math-options-general

```bash
wp option pluck rank-math-options-general strip_category_base    # on/off
wp option pluck rank-math-options-general breadcrumbs            # on/off
wp option pluck rank-math-options-general knowledgegraph_type    # person/company
wp option pluck rank-math-options-general url                    # URL empresa
wp option pluck rank-math-options-general name                   # Nome empresa/pessoa
```

### Sub-keys rank-math-options-titles

```bash
wp option pluck rank-math-options-titles title_separator          # - / | • …
wp option pluck rank-math-options-titles homepage_title           # Título homepage
wp option pluck rank-math-options-titles homepage_description     # Desc homepage
wp option pluck rank-math-options-titles pt_post_title            # Título padrão posts
wp option pluck rank-math-options-titles pt_page_title            # Título padrão pages
wp option pluck rank-math-options-titles pt_product_title         # Título padrão products
```

### Sub-keys rank-math-options-sitemap

```bash
wp option pluck rank-math-options-sitemap items_per_page         # Default: 200
wp option pluck rank-math-options-sitemap pt_post_sitemap        # on/off
wp option pluck rank-math-options-sitemap pt_page_sitemap        # on/off
wp option pluck rank-math-options-sitemap pt_product_sitemap     # on/off
wp option pluck rank-math-options-sitemap pt_attachment_sitemap  # on/off (default: off)
```

---

## Módulos Rank Math

```bash
# Ver todos os módulos
wp option get rank_math_modules --format=json --allow-root

# Activar módulo
wp option patch update rank_math_modules MODULE_NAME "1" --allow-root

# Desactivar módulo
wp option patch update rank_math_modules MODULE_NAME "0" --allow-root
```

| Módulo | Slug | Função |
|--------|------|--------|
| SEO Analysis | `seo-analysis` | Score SEO no editor |
| Link Counter | `link-counter` | Contagem links internos/externos |
| Redirections | `redirections` | Sistema de redirects |
| 404 Monitor | `404-monitor` | Log de 404s |
| Schema | `rich-snippet` | Schema markup |
| Sitemap | `sitemap` | XML Sitemap |
| Instant Indexing | `instant-indexing` | Google Indexing API (PRO) |
| Local SEO | `local-seo` | Schema LocalBusiness |
| WooCommerce | `woocommerce` | SEO WooCommerce |

---

## Leitura de Meta

```bash
# Todos os meta do post
wp post meta list 42 --format=table --allow-root | grep rank_math

# Meta específico
wp post meta get 42 rank_math_title --allow-root
wp post meta get 42 rank_math_description --allow-root
wp post meta get 42 rank_math_robots --allow-root

# Meta de term
wp term meta get 15 rank_math_title --allow-root
wp term meta get 15 rank_math_description --allow-root
```

---

## Operações em Massa

### Script de auditoria completo

```bash
#!/bin/bash
PATH_WP="/home/USER/public_html"
WP="/opt/alt/php-fpm83/usr/bin/php /usr/local/bin/wp --allow-root --path=$PATH_WP"

echo "=== AUDITORIA RANK MATH SEO ==="
echo "Site: $PATH_WP"
echo "Data: $(date)"

echo -e "\n--- Posts sem título SEO ---"
$WP db query "SELECT p.ID, LEFT(p.post_title,50) as titulo FROM wp_posts p
LEFT JOIN wp_postmeta pm ON p.ID=pm.post_id AND pm.meta_key='rank_math_title'
WHERE p.post_type='post' AND p.post_status='publish'
AND (pm.meta_value IS NULL OR pm.meta_value='')
LIMIT 20;"

echo -e "\n--- Posts sem descrição SEO ---"
$WP db query "SELECT p.ID, LEFT(p.post_title,50) as titulo FROM wp_posts p
LEFT JOIN wp_postmeta pm ON p.ID=pm.post_id AND pm.meta_key='rank_math_description'
WHERE p.post_type='post' AND p.post_status='publish'
AND (pm.meta_value IS NULL OR pm.meta_value='')
LIMIT 20;"

echo -e "\n--- Top 10 404s ---"
$WP db query "SELECT uri, SUM(times_accessed) as total FROM wp_rank_math_404_logs
GROUP BY uri ORDER BY total DESC LIMIT 10;"

echo -e "\n--- Módulos activos ---"
$WP option get rank_math_modules --format=json

echo -e "\n--- Tamanho options ---"
$WP db query "SELECT option_name, LENGTH(option_value) as bytes FROM wp_options
WHERE option_name LIKE 'rank%' AND autoload='yes' ORDER BY bytes DESC;"

echo "=== FIM AUDITORIA ==="
```

### Bulk: Aplicar título padrão a posts sem título

```bash
wp eval '
$posts = get_posts(["post_type"=>"post","numberposts"=>-1,"post_status"=>"publish"]);
$updated = 0;
foreach ($posts as $p) {
    if (!get_post_meta($p->ID, "rank_math_title", true)) {
        update_post_meta($p->ID, "rank_math_title", "%title% %sep% %sitename%");
        $updated++;
    }
}
echo "$updated posts actualizados\n";
' --allow-root --path=$PATH_WP
```

### Bulk: Aplicar descrição a partir do excerpt

```bash
wp eval '
$posts = get_posts(["post_type"=>"post","numberposts"=>-1,"post_status"=>"publish"]);
$updated = 0;
foreach ($posts as $p) {
    if (!get_post_meta($p->ID, "rank_math_description", true) && $p->post_excerpt) {
        $desc = wp_trim_words($p->post_excerpt, 20, "...");
        update_post_meta($p->ID, "rank_math_description", $desc);
        $updated++;
    }
}
echo "$updated posts actualizados\n";
' --allow-root --path=$PATH_WP
```

---

## Schema — Exemplos Completos

### Article (blog post)

```bash
wp eval '
$post_id = ID;
update_post_meta($post_id, "rank_math_schema_Article", [
    "metadata" => [
        "title"=>"Article",
        "type"=>"custom",
        "shortcode"=>"s-".uniqid(),
        "isPrimary"=>"1"
    ],
    "@type"=>"Article",
    "headline"=>"%seo_title%",
    "description"=>"%seo_description%",
    "url"=>"%url%",
    "author"=>["@type"=>"Person","name"=>"%name%"],
    "publisher"=>["@type"=>"Organization","name"=>"%sitename%","logo"=>""],
    "datePublished"=>"%date(Y-m-dTH:i:sP)%",
    "dateModified"=>"%modified(Y-m-dTH:i:sP)%",
    "image"=>"%post_thumbnail%"
]);
echo "Article schema criado no post $post_id\n";
' --user=1 --allow-root --path=$PATH_WP
```

### LocalBusiness (página contacto)

```bash
wp eval '
update_post_meta(ID, "rank_math_schema_LocalBusiness", [
    "metadata" => ["title"=>"LocalBusiness","type"=>"custom","shortcode"=>"s-".uniqid(),"isPrimary"=>"1"],
    "@type"=>"LocalBusiness",
    "name"=>"Nome Empresa",
    "description"=>"%seo_description%",
    "url"=>"%url%",
    "email"=>"email@empresa.pt",
    "telephone"=>"+351 XXX XXX XXX",
    "address"=>["@type"=>"PostalAddress","streetAddress"=>"Rua X","addressLocality"=>"Cidade","postalCode"=>"XXXX-XXX","addressCountry"=>"PT"],
    "geo"=>["@type"=>"GeoCoordinates","latitude"=>"38.7","longitude"=>"-9.1"],
    "openingHoursSpecification"=>[
        ["@type"=>"OpeningHoursSpecification","dayOfWeek"=>["Monday","Tuesday","Wednesday","Thursday","Friday"],"opens"=>"09:00","closes"=>"18:00"]
    ],
    "image"=>"%post_thumbnail%"
]);
echo "LocalBusiness schema criado\n";
' --user=1 --allow-root --path=$PATH_WP
```

---

## Instant Indexing (Google Indexing API - PRO)

```bash
# Submeter URL individual
wp eval '\RankMath\Instant_Indexing\Api::submit("https://site.pt/url/", "URL_UPDATED"); echo "OK\n";' --allow-root --path=$PATH_WP

# Verificar estado da API
wp option pluck rank-math-options-instant-indexing bing_api_key --allow-root --path=$PATH_WP
```

---

## Redirects — Referência Completa

### Tipos de Comparação

| comparison | Comportamento |
|-----------|---------------|
| `exact` | Match exacto do URL |
| `contains` | URL contém o pattern |
| `starts_with` | URL começa com o pattern |
| `ends_with` | URL termina com o pattern |
| `regex` | Regular expression |

### Códigos HTTP

| Código | Tipo | Uso |
|--------|------|-----|
| 301 | Moved Permanently | Redirect definitivo |
| 302 | Found | Redirect temporário |
| 307 | Temporary Redirect | Temporário (preserva método HTTP) |
| 410 | Gone | Conteúdo removido permanentemente |
| 451 | Unavailable For Legal | Removido por razões legais |

---

## Tabelas Rank Math — Verificação

```bash
# Ver tabelas custom
wp db query "SHOW TABLES LIKE '%rank_math%';" --allow-root --path=$PATH_WP

# Estrutura tabela redirections
wp db query "DESCRIBE wp_rank_math_redirections;" --allow-root --path=$PATH_WP

# Ver todos os redirects activos
wp db query "SELECT id, sources, url_to, header_code FROM wp_rank_math_redirections WHERE status='active';" --allow-root --path=$PATH_WP
```

---

## Free vs PRO — Funcionalidades WP-CLI

| Funcionalidade | Free | PRO | Notas |
|---------------|------|-----|-------|
| `wp rankmath sitemap generate` | ✅ | ✅ | Único comando nativo |
| Meta por post | ✅ | ✅ | `wp post meta` |
| Options globais | ✅ | ✅ | `wp option patch` |
| Schema markup | ✅ | ✅ | `wp eval` |
| Redirections | ✅ | ✅ | `\RankMath\Redirections\DB` |
| 404 Monitor | ✅ | ✅ | `wp_rank_math_404_logs` |
| Instant Indexing | ❌ | ✅ | `\RankMath\Instant_Indexing\Api` |
| Analytics GSC | ❌ | ✅ | Tabelas analytics_gsc |
| Analytics GA | ❌ | ✅ | Tabelas analytics_ga |

---

*Referência Rank Math WP-CLI | Descomplicar® | v1.0.0 | 18-02-2026*
