What characters are allowed as a shortcode tag and how should they be sanitized?

You can use almost every character. Just the character / is dangerous. Do not allow it. WordPress is using preg_quote to escape the shortcode name, but it doesn’t include its own regex delimiter / when doing that. So the shortcode will not be properly escaped and you get a PHP warning.

Besides that, there are just two basic rules for a shortcode name:

  1. It should be at least two characters long.
  2. It should contain at least one US-ASCII character (a-z0-9).

So this works:

foreach ( array ( '.-o', ']b', 'äoß', 'o"o', "o'o", '❤m' ) as $shortcode )
{
    add_shortcode( $shortcode, 't5_crazy_shortcode_handler' );
}

function t5_crazy_shortcode_handler( $attrs = array(), $content = NULL, $shortcode )
{
    return "<pre>\$shortcode: $shortcode\n\n\$attrs\n"
        . htmlspecialchars( print_r( $attrs, TRUE ) )
        . "\n\n\$content"
        . htmlspecialchars( print_r( $content, TRUE ) )
        . '</pre>';
}

Leave a Comment