WordPress 2.5 Shortcodes

Warning: Shortcodes are affected by Trac ticket 6444, which should be applied to WordPress 2.5.1.

First I touched on the topic in my first impressions of WordPress 2.5. Then I whined a little about the tickets relating to them, and eventually I released my Google Maps Plugin that uses them. In the end, WordPress’s new shortcodes are really nice.

What are they?

First of all, a shortcode called “mycode” can look like any of these:
[mycode]
[mycode foo="bar" id="123" color="red" something="data"]
[mycode]Some Content[/mycode]
[mycode]<p><a href="http://example.com/">HTML Content</a></p>[/mycode]
[mycode]Content [another-shotcode] more content[/mycode]
[mycode foo="bar" id="123"]Some Content[/mycode]

As you can see, shortcodes allow a user to put a code into a post or page, and a plugin can then easily handle those codes. They can be nested, contain content (including HTML), attributes, etc.

How can I use them?

First of all, you need to add your shortcode:
add_shortcode('mycode', 'yourFunction');
Your function should take two arguments and return the content that you want to replace the shortcode with. The first argument will be an associative array of attributes (keys will be the attribute names, and the value will be the corresponding attribute value), and the second will be the content between the tags.

To handle default attributes, you can use shortcode_atts($defaultsArray, $attributesArray):

function yourFunction ($attr, $content) {
    $attr = shortcode_atts(array('foo' => 'bar', 'id' => '','color' => 'blue'), $attr);
    return '<h2>Attributes</h2><pre>' . print_r($attr, true) . '</pre><h2>content</h2>' . $content;
}

That’s it! That’s why they are so great, it takes next to nothing to handle! However, maybe you’re thinking about a relatively complex way to use these, and you want to take it to the next level.

The Next Level

Maybe you’re worried that you’re users won’t grasp the intricacies of your shortcodes, or will be plagued by typos. It’s a valid concern. For example, I don’t want to assume that my users will be able to create a Google map by flawlessly entering:
[googleMap width="100%" height="400" name="Aero Rental - Phoenix" directions_to="true" directions_from="true"]3432 W. Clarendon, 85017[/googleMap]

The solution is to create a way for your users to generate the shortcodes and have them sent to the editor, but where to start? First, you need to add a meta box to the writing/editing pages (these are the dropdown boxes below the editor, such as Tags, Categories, etc). To do this, create a function that you will use to display the form used to generate your shortcode. Then you need to hook into the admin_menu action, and use it to create the metaboxes.

View the complete solution to complex shortcodes in WordPress 2.5.

Leave a Reply