Wordpress shortcodes to the rescue

Do you really trust your users' HTML skills?

Wordpress shortcodes allow us to quickly and easily build somewhat complex markup constructs wrapped around user entered copy, without the editor knowing complicated markup and without the need for a completely separate and complex Wordpress plugin.

Today we were working on a site for a client using Wordpress that required some markup wrapped around a block of copy the user was to enter using the standard CMS copy entry. For someone who knows HTML it was trivially simple, however when working with WP and any other client-facing-CMS having users who know any HTML is highly unlikely. To get around this Wordpress allows for you to quickly and easily implement shortcodes that, while not beginner CMS level, allow users to simply add possibly complicated markup without realizing.

For the content editor to use a shortcode they only need to enter something like:

[block title="Lorem ipsum dolor"]
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

This will allow us to build any HTML markup we want with the specific elements provided. To do so we load up our functions.php file in the theme we're building and get to it.

function block_shortcode($atts, $content="") {

        'title' => false
    ), $atts));

    $html = "<div class=\"block\">" .
    $html .= ($title) ? "<h2>$title</h2>" : "";
    $html .= "<div class=\"copy\">$content</div>";
    $html .= "</div>";

    return $html;
add_shortcode('block', 'block_shortcode');

The code above is trivially simple, but perfect for this example. We knocked up a simple function which takes the attributes passed to the short code (in this case we're only using title, though you can have as many as you want) and the content which is passed as the short code method's second parameter (but remember it may not be passed at all!).

The function itself simply runs extract to make all the $attr array variables local (which I'm not a fan of, but it's standard practice with these short codes. Another PHP-ism I guess… meh). After that we build the HTML markup with some more dirty PHP code. We at least check for an existing title before we use it.

The last line is how we actually add the short code to the Wordpress instance. This method add_shortcode takes the short code name to use (e.g. [block xxx]) and the function to call when it's placed in users content. With that extremely simple code you can create some really nice user-functions without forcing them to understand any HTML themselves. Win win!