# Output Escaping > Úsalo al mostrar o imprimir cualquier valor dinámico en PHP o plantillas de WordPress, escapando en el punto de salida con esc_html, esc_attr, esc_url, esc_js, esc_textarea o wp_kses_post para prevenir XSS. Fuente: https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/output-escaping Markdown: https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/output-escaping.md Repositorio: https://github.com/wpultimatesecurity/WordPress-Security-Skills Autor: wpultimatesecurity Licencia: MIT Actualizado: hace 2 meses Coste de contexto: 102 tok instalada, 2.4k tok al activarse, 3.3k tok con todos los archivos del bundle Bundle: 3 archivos, 13 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 output-escaping --agent claude-code # Cursor npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill output-escaping --agent cursor # Codex npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill output-escaping --agent codex # Gemini CLI npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill output-escaping --agent gemini # Windsurf npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill output-escaping --agent windsurf # Cline npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill output-escaping --agent cline ``` ## Qué hace - Escapa cada valor dinámico en el punto de salida usando esc_html, esc_attr, esc_url, esc_js, esc_textarea o wp_kses_post según el contexto - Aplica las variantes i18n (esc_html__, esc_attr_e) a cadenas traducidas antes de imprimirlas - Valida y sanea URLs de redirección con esc_url_raw, wp_validate_redirect y wp_safe_redirect - Revisa el código JavaScript para evitar sinks DOM peligrosos como innerHTML o .html() ## Cuándo usarla - Al hacer echo o print de cualquier variable dentro de HTML, atributos, URLs, JS inline o textareas - Al renderizar contenido en plantillas, shortcodes, bloques, widgets o respuestas REST que devuelven HTML - Al pasar datos a wp_localize_script o insertarlos mediante JavaScript en el DOM - Al construir un redirect con un valor de $_GET u otro origen externo ## Qué la activa - "Revisa si estoy escapando bien esta variable antes de hacer echo en mi plantilla" - "¿Qué función de escaping debo usar para este atributo href?" - "Comprueba si mi código es vulnerable a XSS almacenado" - "Ayúdame a corregir este wp_redirect inseguro" ## Archivos - SKILL.md — 9 KB - references/checklist.md — 754 B - references/escaping-cheatsheet.md — 3 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. # Output escaping (XSS prevention) ## When to use this skill Use this skill whenever a **dynamic value is sent to the browser**: - `echo` / `print` of any variable into HTML. - Values placed into HTML attributes (`value`, `href`, `src`, `class`, `data-*`). - URLs in `href` / `src` / redirects. - Data injected into inline `'; ``` ```php // ✅ Secure: esc_js for a single quoted string... echo ''; // ...or, better, pass structured data as JSON: echo ''; ``` ### Mistake 5 — Using `wp_kses_post()` where escaping is required (and vice versa) ```php // ❌ Wrong tool: kses lets markup through where you wanted plain text. echo '' . wp_kses_post( $plain_title ) . ''; ``` ```php // ✅ Plain text → esc_html; intentional rich HTML → wp_kses_post. echo '' . esc_html( $plain_title ) . ''; echo '
' . wp_kses_post( $rich_bio ) . '
'; ``` ### Mistake 6 — Translated strings echoed unescaped ```php // ❌ Insecure: translation files can contain markup; raw echo into a tag. echo '

' . __( 'Welcome, %s', 'my-plugin' ) . '

'; ``` ```php // ✅ Secure: escape the translated output. printf( '

%s

', esc_html__( 'Welcome back', 'my-plugin' ) ); ``` ### Mistake 7 — Redirect target not validated ```php // ❌ Insecure: open redirect to an attacker-controlled site. $redirect = $_GET['redirect_to']; wp_redirect( $redirect ); exit; ``` ```php // ✅ Secure: the "escape" for a Location target is validation + wp_safe_redirect. $redirect = isset( $_GET['redirect_to'] ) ? esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) : ''; $redirect = wp_validate_redirect( $redirect, admin_url() ); wp_safe_redirect( $redirect ); exit; ``` ### Mistake 8 — Using wp_kses_post where a tighter allowlist is needed ```php // ❌ Risky: wp_kses_post allows many tags you may not want in a caption. echo wp_kses_post( $caption ); ``` ```php // ✅ Secure: define a custom allowlist when the context is narrower. $allowed = array( 'a' => array( 'href' => array() ), 'em' => array(), 'strong' => array(), ); echo wp_kses( $caption, $allowed ); ``` Related: see the `input-sanitization-validation` skill for validating redirect URLs on input and the `filesystem-security` skill for path escaping. ### Mistake 9 — Escaping in PHP, then re-injecting in JavaScript ```js // ❌ Insecure: PHP passed the value safely through wp_localize_script or // wp_json_encode, but the script decodes it into markup. const name = myPluginData.displayName; document.querySelector( '#greeting' ).innerHTML = 'Hello ' + name; jQuery( '#title' ).html( myPluginData.title ); ``` ```js // ✅ Secure: insert untrusted values as text in the DOM. document.querySelector( '#greeting' ).textContent = 'Hello ' + myPluginData.displayName; jQuery( '#title' ).text( myPluginData.title ); ``` Server-side escaping protects the transfer into the page, not what client code does next. Review DOM sinks (`innerHTML`, `outerHTML`, `insertAdjacentHTML`, `document.write`, jQuery `.html()`/`.append()` with strings, `location` assignments) in plugin scripts. ## Correct code examples A complete context → function reference (with `esc_url` vs `esc_url_raw`, the i18n variants, and `wp_kses` allowlist usage) is in [`references/escaping-cheatsheet.md`](references/escaping-cheatsheet.md). ```php // A small template snippet that escapes every dynamic value in context. ?>