---
name: rank-math
description: Gestão do plugin Rank Math SEO via WP-CLI em servidores CWP. Cobre auditoria SEO, configuração em massa de títulos e meta descriptions, schema markup, redirects e sitemaps.
---

# /rank-math - Gestão Rank Math SEO via WP-CLI

Operações de SEO WordPress via WP-CLI no servidor CWP (server.descomplicar.pt). Cobre auditoria, configuração em massa, schema markup, redirects e sitemap.

**Manual completo:** `Hub/06-Operacoes/Documentacao/Manuais/Rank-Math-WP-CLI-Manual-Definitivo.md`
**Quick Reference:** `Hub/06-Operacoes/Documentacao/Quick-Reference/QR-RankMath-WP-CLI.md`
**NotebookLM:** [WordPress Config CLI](https://notebooklm.google.com/notebook/fb2f26bd-8cb0-4d4c-bafc-4f1ebb51c51d)

---

## Contexto NotebookLM

ANTES de executar, consultar notebooks para contexto especializado:

| Notebook | ID | Consultar quando |
|----------|-----|-----------------|
| WordPress e Elementor | 5be0d1a6 | Sempre |
| Marketing Digital PT | 4c595973 | Para contexto SEO |

```
mcp__notebooklm__notebook_query({
  notebook_id: "5be0d1a6-00f2-4cd9-b835-978cb7721601",
  query: "<adaptar ao contexto do pedido do utilizador>"
})

mcp__notebooklm__notebook_query({
  notebook_id: "4c595973-ba10-420a-a3bf-e4389e424ad3",
  query: "<adaptar ao contexto SEO do pedido>"
})
```

Integrar insights do NotebookLM nas recomendações e decisões.

---

## Uso

```
/rank-math audit https://site.pt
/rank-math update-meta /home/USER/public_html
/rank-math sitemap /home/USER/public_html
/rank-math redirects /home/USER/public_html
/rank-math schema post ID /home/USER/public_html
```

---

## Contexto CWP — Sempre Obrigatório

**PHP 8.3 no CWP:**
```bash
# Formato base
/opt/alt/php-fpm83/usr/bin/php /usr/local/bin/wp <comando> --allow-root --path=/home/USER/public_html

# Alias ~/.bashrc (se configurado)
wp83 <comando> --allow-root --path=/home/USER/public_html
```

**Acesso via MCP SSH:**
```
servidor: server.descomplicar.pt (176.9.3.158)
porta: 9443 | user: root
```

**Único comando nativo Rank Math:**
```bash
wp rankmath sitemap generate --allow-root --path=/home/USER/public_html
```
Tudo o resto usa `wp post meta`, `wp option patch`, `wp eval` ou `wp db query`.

---

## Workflow: Auditoria SEO (/rank-math audit)

### Passo 1 — Diagnóstico rápido

```bash
PATH=/home/USER/public_html

# Posts sem título SEO
wp db query "SELECT p.ID, p.post_title 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='');" --allow-root --path=$PATH

# Posts sem descrição SEO
wp db query "SELECT p.ID, p.post_title 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='');" --allow-root --path=$PATH

# Top 404s (últimos 30 dias)
wp db query "SELECT uri, SUM(times_accessed) as total FROM wp_rank_math_404_logs
GROUP BY uri ORDER BY total DESC LIMIT 20;" --allow-root --path=$PATH

# Tamanho options (detetar bloat WooCommerce)
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;" --allow-root --path=$PATH
```

### Passo 2 — Estado módulos

```bash
wp option pluck rank_math_modules --allow-root --path=$PATH
wp option pluck rank-math-options-general strip_category_base --allow-root --path=$PATH
wp option pluck rank-math-options-titles title_separator --allow-root --path=$PATH
```

---

## Workflow: Actualizar Meta SEO (/rank-math update-meta)

### Meta key individual

```bash
# Título SEO
wp post meta update ID rank_math_title "%title% %sep% %sitename%" --allow-root --path=$PATH

# Descrição SEO (<160 chars)
wp post meta update ID rank_math_description "Texto conciso da página." --allow-root --path=$PATH

# Focus keyword
wp post meta update ID rank_math_focus_keyword "keyword1,keyword2" --allow-root --path=$PATH

# Robots (ARRAY JSON — obrigatório --format=json)
wp post meta update ID rank_math_robots '["noindex"]' --format=json --allow-root --path=$PATH

# Canonical URL
wp post meta update ID rank_math_canonical_url "https://site.pt/url/" --allow-root --path=$PATH

# Pillar content
wp post meta update ID rank_math_pillar_content "on" --allow-root --path=$PATH
```

### Bulk update (wp eval)

```bash
# Aplicar título padrão a todos os posts sem título
wp eval '
$posts = get_posts(["numberposts"=>-1,"post_status"=>"publish"]);
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%");
    }
}
echo count($posts)." posts processados\n";
' --allow-root --path=$PATH
```

---

## Workflow: Options Globais (/rank-math options)

**Regra crítica:** SEMPRE usar `wp option patch`, NUNCA `wp option update` em options serializadas.

```bash
# Separador de título
wp option patch update rank-math-options-titles title_separator "-" --allow-root --path=$PATH

# Remover base de categoria do URL
wp option patch update rank-math-options-general strip_category_base "on" --allow-root --path=$PATH

# Verificar sub-key
wp option pluck rank-math-options-titles title_separator --allow-root --path=$PATH

# LER option completa (diagnóstico)
wp option get rank-math-options-general --format=json --allow-root --path=$PATH
```

---

## Workflow: Schema Markup (/rank-math schema)

Schema é armazenado como array PHP em `rank_math_schema_{Type}`. Usar `wp eval` (não JSON directo).

```bash
# Criar schema Article num post
wp eval '
update_post_meta(ID, "rank_math_schema_Article", [
    "metadata" => ["title"=>"Article","type"=>"custom","shortcode"=>"s-".uniqid(),"isPrimary"=>"1"],
    "@type"=>"Article",
    "headline"=>"%seo_title%",
    "description"=>"%seo_description%",
    "author"=>["@type"=>"Person","name"=>"%name%"],
    "datePublished"=>"%date(Y-m-dTH:i:sP)%",
    "dateModified"=>"%modified(Y-m-dTH:i:sP)%"
]);
echo "Schema criado\n";
' --user=1 --allow-root --path=$PATH

# Criar schema FAQ
wp eval '
update_post_meta(ID, "rank_math_schema_FAQPage", [
    "metadata" => ["title"=>"FAQ","type"=>"custom","shortcode"=>"s-".uniqid(),"isPrimary"=>"1"],
    "@type"=>"FAQPage",
    "mainEntity"=>[
        ["@type"=>"Question","name"=>"Pergunta 1","acceptedAnswer"=>["@type"=>"Answer","text"=>"Resposta 1"]],
        ["@type"=>"Question","name"=>"Pergunta 2","acceptedAnswer"=>["@type"=>"Answer","text"=>"Resposta 2"]]
    ]
]);
echo "FAQ Schema criado\n";
' --user=1 --allow-root --path=$PATH

# Apagar schema corrompido
wp post meta delete ID rank_math_schema_Article --allow-root --path=$PATH
```

---

## Workflow: Redirects (/rank-math redirects)

```bash
# Criar redirect 301
wp eval '
\RankMath\Redirections\DB::add([
    "id"=>"",
    "sources"=>[["pattern"=>"/url-antiga/","comparison"=>"exact"]],
    "url_to"=>"/url-nova/",
    "header_code"=>301,
    "status"=>"active",
]);
echo "Redirect criado\n";
' --allow-root --path=$PATH

# Redirect com wildcard
wp eval '
\RankMath\Redirections\DB::add([
    "id"=>"",
    "sources"=>[["pattern"=>"/blog/","comparison"=>"contain"]],
    "url_to"=>"/artigos/",
    "header_code"=>301,
    "status"=>"active",
]);
echo "Redirect wildcard criado\n";
' --allow-root --path=$PATH

# Apagar redirect por ID
wp eval '\RankMath\Redirections\DB::delete(42); echo "Redirect apagado\n";' --allow-root --path=$PATH

# Limpar logs 404 (após resolver)
wp db query "TRUNCATE TABLE wp_rank_math_404_logs;" --allow-root --path=$PATH
```

---

## Workflow: Sitemap (/rank-math sitemap)

```bash
# Regenerar sitemap
wp rankmath sitemap generate --allow-root --path=$PATH

# Excluir post-type do sitemap
wp option patch update rank-math-options-sitemap pt_attachment_sitemap "off" --allow-root --path=$PATH

# Verificar setting
wp option pluck rank-math-options-sitemap pt_post_sitemap --allow-root --path=$PATH
```

---

## Sequência de Cache (Sempre Após Alterações)

```bash
wp cache flush --allow-root --path=$PATH
wp transient delete --all --allow-root --path=$PATH
wp rewrite flush --allow-root --path=$PATH
wp rankmath sitemap generate --allow-root --path=$PATH
```

> Alterações via `wp db query` não invalidam Redis/Memcached. Sempre executar `wp cache flush`.

---

## Gotchas Críticos

| Problema | Causa | Solução |
|----------|-------|---------|
| Robots não aplicam | Injectado como string, não array | `'["noindex"]' --format=json` |
| Options corrompidas | `wp option update` em option serializada | Sempre `wp option patch` |
| Alteração não visível | Object cache (Redis) em memória | `wp cache flush` |
| Schema quebra editor | JSON inválido em `rank_math_schema_*` | `wp post meta delete ID rank_math_schema_*` |
| Sitemap 404 no Nginx | Faltam rewrite rules | Adicionar regras ao server block |

---

## Variáveis Dinâmicas Frequentes

`%title%` · `%sitename%` · `%sep%` · `%excerpt%` · `%category%` · `%currentyear%` · `%seo_title%` · `%seo_description%` · `%post_thumbnail%` · `%url%` · `%name%`

---

## Recursos Adicionais

### Referências

- **`references/commands.md`** — Referência completa de todos os comandos, meta keys, options e módulos

### Documentação Hub

- **Manual:** `Hub/06-Operacoes/Documentacao/Manuais/Rank-Math-WP-CLI-Manual-Definitivo.md` (17 secções)
- **QR:** `Hub/06-Operacoes/Documentacao/Quick-Reference/QR-RankMath-WP-CLI.md`
- **NotebookLM:** [WordPress Config CLI](https://notebooklm.google.com/notebook/fb2f26bd-8cb0-4d4c-bafc-4f1ebb51c51d) (4 fontes)

---

*Rank Math SEO via WP-CLI | Descomplicar® | v1.0.0 | 18-02-2026*
