Escaping API updates for WordPress 2.8

The WordPress escaping API functions have been updated. Escaping is a way of using untrusted text that “neuters” anything that could do damage. Escaping is used in WordPress to avoid SQL injection and cross-site scripting/script injection (XSS), among other things.

The old functions still work, so if you were using the old ones, you’re fine. The new ones just offer you an easier to remember, more concise, and more flexible way of securing your WordPress code.

Here’s an example. Say you wanted to translate a string, escape it for use in a quoted HTML attribute, and then echo it out. In WP 2.7, you’d have to do this:

<?php echo attribute_escape( __( 'Untranslated text' ) ); ?>

In WordPress 2.8, you can just do this:

<?php esc_attr_e( 'Untranslated text' ); ?>

Shorter, plus we killed the echo and the extra pair of parenthesis! But let’s break it down.

esc_ = 1, attr = 2, _e = 3

  1. esc_ is the prefix for the new WP escaping functions.
  2. attr is the context (in this case, attribute). The available contexts for 2.8 are attr, html, js, sql, url, and url_raw.
  3. _e is the optional translation suffix. The available suffixes for 2.8 are __, and _e. If you omit the suffix, no translation is performed, and your string is just returned.

More about contexts

  • attr means an HTML attribute.
  • html means text within an HTML node, but not within an attribute
  • sql is an alias to $wpdb->escape().
  • url means URLs for use in HTML attributes.
  • url_raw means URLs for use in redirects or storage in the database (does not entity-encode).
  • js means JS, for using PHP to populate a Javascript var.

More about suffixes

Suffixes work just like the function they’re named after.

  • __ translates the string and returns it.
  • _e translates the string and echoes it.
  • The suffix is optional. A blank suffix will just return.
  • Suffixes are currently only available for html and attr contexts.

Functions with translation suffixes also accept an option second parameter of a translation domain, for use in plugins.

Enjoy! Go forth and write more succinct code.