# Settings Options Security
> Úsalo al crear una página de ajustes con la Settings API: añade sanitize_callback, gatea con manage_options, usa el nonce del Settings API y escapa las opciones al mostrarlas.
Fuente: https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/settings-options-security
Markdown: https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/settings-options-security.md
Repositorio: https://github.com/wpultimatesecurity/WordPress-Security-Skills
Autor: wpultimatesecurity
Licencia: MIT
Actualizado: hace 2 meses
Coste de contexto: 102 tok instalada, 2.3k tok al activarse, 3.5k tok con todos los archivos del bundle
Bundle: 3 archivos, 14 KB
Permisos que pide: ninguno declarado
## Instalación
Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina.
```bash
# Claude Code
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill settings-options-security --agent claude-code
# Cursor
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill settings-options-security --agent cursor
# Codex
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill settings-options-security --agent codex
# Gemini CLI
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill settings-options-security --agent gemini
# Windsurf
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill settings-options-security --agent windsurf
# Cline
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill settings-options-security --agent cline
```
## Qué hace
- Añade sanitize_callback a cada setting registrado con register_setting()
- Gatea la página de ajustes con manage_options
- Usa settings_fields() para el nonce del Settings API
- Escapa los valores de get_option() en el output
- Sanitiza recursivamente opciones de tipo array/object
## Cuándo usarla
- Construyes una página de ajustes con register_setting, add_settings_field o settings_fields
- Un formulario envía datos a options.php
- Llamas a update_option() o add_option() desde un handler personalizado
- Lees opciones con get_option() y las muestras en admin, front-end o emails
## Qué la activa
- "Crea una página de ajustes segura con la Settings API"
- "Revisa mi register_setting, ¿falta el sanitize_callback?"
- "¿Cómo escapo correctamente los valores de get_option()?"
- "Quiero exponer mis settings por REST con show_in_rest"
## Archivos
- SKILL.md — 9 KB
- references/checklist.md — 723 B
- references/secure-settings-page.php — 4 KB
## SKILL.md
Reproducido tal cual desde wpultimatesecurity/WordPress-Security-Skills bajo MIT. Esta sección es el documento original y está en inglés.
# Settings & options security
## When to use this skill
Use this skill whenever a plugin or theme stores configuration in WordPress options:
- Building a settings page with the Settings API (`register_setting`, `add_settings_section`,
`add_settings_field`).
- A form that posts to `options.php`.
- Calling `update_option()` or `add_option()` from a custom handler.
- Reading options with `get_option()` and rendering them anywhere (admin, front-end, emails).
The Settings API gives you nonce handling, capability gating, and a structured
sanitization hook for free — but only if you actually wire it. Bypassing it for a
"quick" custom form is a common source of stored XSS and unauthorized writes.
Related: see the `input-sanitization-validation` skill for per-request sanitization
patterns and the `nonces-csrf-protection` skill for custom-form nonce handling.
## Core principles (and why they matter)
1. **Every registered setting needs a `sanitize_callback`.** This is the single most
important line of defense against stored XSS and malformed data. Without it,
`update_option()` saves raw `$_POST` values verbatim.
2. **The Settings API supplies the nonce only when you use `settings_fields()`.** If you
build a custom form that calls `options.php`, include `settings_fields( $option_group )`
or you lose CSRF protection.
3. **Options are untrusted on read.** Even if you sanitized on save, escape again on output.
A compromised database, a bad import, or a future bug can reintroduce dangerous values.
4. **Gate the page with a capability, not just a menu position.** `add_options_page()`
already requires `manage_options` by default; custom menus should too.
5. **Use typed defaults.** Pass a `default` value to `register_setting()` so `get_option()`
returns a known shape instead of `false`.
6. **If you expose settings via REST (`show_in_rest`), provide a schema.** Untyped REST
options are another stored-XSS vector.
## Step-by-step implementation
1. On `admin_init`, call `register_setting()` with:
- `option_group` matching the page.
- `option_name` for the stored option.
- `sanitize_callback` pointing to a strict sanitizer.
- `default` with a safe value.
2. Add sections and fields with `add_settings_section()` and `add_settings_field()`.
3. Render the form posting to `options.php` and call `settings_fields( $option_group )`.
4. In field callbacks, escape the current option value with `esc_attr()` / `esc_textarea()`.
5. For custom (non-`options.php`) handlers, add your own `wp_nonce_field()` and verify it with
`check_admin_referer()`, plus `current_user_can( 'manage_options' )`.
6. When displaying saved options anywhere, escape for the output context.
### Supporting references
| Reference | Load when |
| --- | --- |
| [Settings & options security checklist](references/checklist.md) | Before final verification of the settings & options security controls. |
| [Secure Settings API page](references/secure-settings-page.php) | Implementing a sanitized Settings API page with an options.php form and escaped output. |
## Common AI mistakes / anti-patterns
### Mistake 1 — `register_setting()` with no sanitize callback
```php
// ❌ Insecure: raw POST data is saved into the option.
register_setting( 'my_plugin_group', 'my_plugin_options' );
```
```php
// ✅ Secure: every setting has a sanitize_callback.
register_setting(
'my_plugin_group',
'my_plugin_options',
array(
'type' => 'array',
'sanitize_callback' => 'my_plugin_sanitize_options',
'default' => array( 'api_key' => '', 'enabled' => 0 ),
)
);
function my_plugin_sanitize_options( $input ) {
$clean = array();
if ( isset( $input['api_key'] ) ) {
$clean['api_key'] = sanitize_text_field( wp_unslash( $input['api_key'] ) );
}
$clean['enabled'] = ! empty( $input['enabled'] ) ? 1 : 0;
return $clean;
}
```
### Mistake 2 — Custom settings form bypassing `settings_fields`
```php
// ❌ Insecure: no nonce, no capability gate, raw option write.
```
### Mistake 3 — Echoing `get_option()` unescaped
```php
// ❌ Insecure: stored XSS if the option contains JavaScript.
echo '' . get_option( 'my_plugin_notice' ) . '
';
```
```php
// ✅ Secure: escape on output for the context.
$notice = get_option( 'my_plugin_notice', '' );
echo '' . esc_html( $notice ) . '
';
```
### Mistake 4 — Not recursively sanitizing array options
```php
// ❌ Insecure: only the top-level array is sanitized; nested strings remain raw.
function my_plugin_sanitize_array( $input ) {
return array_map( 'sanitize_text_field', $input );
}
```
```php
// ✅ Secure: know the schema and sanitize each member.
function my_plugin_sanitize_array( $input ) {
$clean = array();
if ( isset( $input['api_key'] ) ) {
$clean['api_key'] = sanitize_text_field( wp_unslash( $input['api_key'] ) );
}
if ( isset( $input['webhook_url'] ) ) {
$clean['webhook_url'] = esc_url_raw( wp_unslash( $input['webhook_url'] ) );
}
$clean['debug'] = ! empty( $input['debug'] ) ? 1 : 0;
return $clean;
}
```
### Mistake 5 — `show_in_rest => true` with no schema
```php
// ❌ Insecure: REST consumers can write arbitrary shapes to the option.
register_setting(
'my_plugin_group',
'my_plugin_options',
array( 'show_in_rest' => true )
);
```
```php
// ✅ Secure: declare a REST schema so WordPress validates the shape.
register_setting(
'my_plugin_group',
'my_plugin_options',
array(
'type' => 'object',
'show_in_rest' => array(
'schema' => array(
'type' => 'object',
'properties' => array(
'api_key' => array( 'type' => 'string' ),
'enabled' => array( 'type' => 'boolean' ),
),
),
),
'sanitize_callback' => 'my_plugin_sanitize_options',
'default' => array( 'api_key' => '', 'enabled' => false ),
)
);
```
## Correct code examples
A complete Settings API page (registration, section, field, form, sanitization) is in
[`references/secure-settings-page.php`](references/secure-settings-page.php).
## Checklist
- [ ] Every `register_setting()` call includes a `sanitize_callback`.
- [ ] Settings have safe `default` values of the correct type.
- [ ] The settings form posts to `options.php` and calls `settings_fields()`.
- [ ] The admin page is gated by `manage_options` (or a stricter custom capability).
- [ ] Custom non-Settings-API handlers add their own nonce + capability checks.
- [ ] Array/object options are recursively sanitized against a known schema.
- [ ] `get_option()` values are escaped at the point of output.
- [ ] REST-exposed settings (`show_in_rest`) include a schema.
- [ ] Secrets are stored encrypted or in wp-config constants, not plaintext in options.
## Official references
- [Settings API — Plugin Handbook](https://developer.wordpress.org/plugins/settings/)
- [`register_setting()`](https://developer.wordpress.org/reference/functions/register_setting/)
- [`add_settings_section()`](https://developer.wordpress.org/reference/functions/add_settings_section/)
- [`add_settings_field()`](https://developer.wordpress.org/reference/functions/add_settings_field/)
- [`settings_fields()`](https://developer.wordpress.org/reference/functions/settings_fields/)
- [`do_settings_sections()`](https://developer.wordpress.org/reference/functions/do_settings_sections/)
- [`get_option()`](https://developer.wordpress.org/reference/functions/get_option/)
- [`update_option()`](https://developer.wordpress.org/reference/functions/update_option/)
- [`esc_attr()`](https://developer.wordpress.org/reference/functions/esc_attr/)
- [`esc_textarea()`](https://developer.wordpress.org/reference/functions/esc_textarea/)
## Dónde encaja
- Categoría: [Seguridad](https://skillsagentes.com/categorias/seguridad.md) — Auditorías, revisión de dependencias, manejo de secretos y modelado de amenazas.
- Creador: [wpultimatesecurity](https://skillsagentes.com/creators/wpultimatesecurity.md) — 27 skills en el directorio
- [Todas las skills](https://skillsagentes.com/skills.md)
- [Ranking de instalaciones](https://skillsagentes.com/ranking.md)
## Otras skills del mismo repositorio
- [Security Auditing Code Review](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/security-auditing-code-review.md): Úsalo al auditar o revisar código de un plugin o tema WordPress existente, triar un informe de vulnerabilidad o endurecer código heredado, con una metodología sistemática.
- [Authentication Session Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/authentication-session-security.md): Úsalo cuando el código inicia o cierra sesión, gestiona cookies o tokens de sesión, limita intentos de login o construye un formulario de login propio en WordPress.
- [Dependency Supply Chain Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/dependency-supply-chain-security.md): Úsalo cuando un plugin o tema empaquete una librería de terceros, cargue un asset desde un CDN, ejecute código remoto, use Composer o prepare el zip distribuible.
- [Secure Plugin Development](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/secure-plugin-development.md): Úsalo al iniciar un plugin o tema de WordPress, al añadir hooks o funciones que manejan peticiones, opciones o salida; establece la línea base segura por defecto.
- [Gutenberg Block Editor Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/gutenberg-block-editor-security.md): Úsalo al construir bloques dinámicos o funciones del editor de bloques: render_callback, ServerSideRender, datos REST o register_rest_field, para evitar XSS almacenado y control de acceso roto.
## Skills relacionadas
- [Ai Llm Integration Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/ai-llm-integration-security.md): Úsalo al construir o revisar funciones de plugin o tema de WordPress que llaman a un LLM: chatbots, generación de contenido, RAG, agentes con herramientas, Abilities API o exposición MCP.
- [Ajax Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/ajax-security.md): Úsalo al registrar o manejar AJAX en WordPress vía admin-ajax.php: verifica el nonce, comprueba permisos, sanitiza cada campo y responde con wp_send_json_*, evitando CSRF e inyecciones.
- [Authentication Session Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/authentication-session-security.md): Úsalo cuando el código inicia o cierra sesión, gestiona cookies o tokens de sesión, limita intentos de login o construye un formulario de login propio en WordPress.
- [Capability Permission Checks](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/capability-permission-checks.md): Protege operaciones privilegiadas en WordPress con current_user_can() usando la capability correcta (no el rol), checks por objeto y nonce, evitando escalada de privilegios y control de acceso roto.
- [Cron Background Job Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/cron-background-job-security.md): Úsalo al programar eventos cron con wp_schedule_event / wp_schedule_single_event o al escribir el callback. Revalida la autorización contra el contexto guardado, no con current_user_can, y mantiene los secretos fuera de las URLs de cron.
---
Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)