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. Sounds great, but how can you leverage shortcodes for your benefit?

How can I use them?

You want to leverage the new, powerful shortcode system in WordPress 2.5, but where do you start?

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 (I’m going to call it “insertForm”). Then you need to hook into the admin_menu action, and use it to create the metaboxes:

<?php
function handleAdminMenu() {
    // You have to add one to the "post" writing/editing page, and one to the "page" writing/editing page
    add_meta_box('yourMetaBoxID', 'Your Meta Box Title', 'insertForm', 'post', 'normal');
    add_meta_box('yourMetaBoxID', 'Your Meta Box Title', 'insertForm', 'page', 'normal');
}

function insertForm() {
?>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><label for="wpYourPluginName_content"><?php _e('Tag Content:')?></label></th>
                <td>
                    <input type="text" size="40" style="width:95%;" name="wpYourPluginName[content]" id="wpYourPluginName_content" />
                </td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="wpYourPluginName_foo"><?php _e('Foo Attribute:')?></label></th>
                <td>
                    <input type="text" size="40" style="width:95%;" name="wpYourPluginName[foo]" id="wpYourPluginName_foo" />
                </td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="wpYourPluginName_bar"><?php _e('Bar Attribute:')?></label></th>
                <td>
                    <input type="text" size="40" style="width:95%;" name="wpYourPluginName[bar]" id="wpYourPluginName_bar" />
                </td>
            </tr>
        </table>
        <p class="submit">
            <input type="button" onclick="return wpYourPluginAdmin.sendToEditor(this.form);" value="<?php _e('Send Map to Editor &raquo;'); ?>" />
        </p>
<?php
}

function adminHead () {
    if ($GLOBALS['editing']) {
        wp_enqueue_script('wpYourPluginNameAdmin', 'path/to/yourJsFile.js', array('jquery'), '1.0.0');
    }
}

add_action('admin_menu', 'handleAdminMenu');
add_filter('admin_print_scripts', 'adminHead');
?>

The specifics:
yourMetaBoxID becomes the id of the metabox div.
“Your Meta Box Title” will be the displayed title for the metabox.

You may have noticed that the submit button calls some javascript (specifically wpYourPluginAdmin.sendToEditor(this.form)), and we enqueue a JavaScript file. Here is that file:

/**
 * Handle: wpYourPluginNameAdmin
 * Version: 0.0.1
 * Deps: jquery
 * Enqueue: true
 */

var wpYourPluginNameAdmin = function () {}

wpYourPluginNameAdmin.prototype = {
    options           : {},
    generateShortCode : function() {
        var content = this['options']['content'];
        delete this['options']['content'];

        var attrs = '';
        jQuery.each(this['options'], function(name, value){
            if (value != '') {
                attrs += ' ' + name + '="' + value + '"';
            }
        });
        return '[googleMap' + attrs + ']' + content + '[/googleMap]'
    },
    sendToEditor      : function(f) {
        var collection = jQuery(f).find("input[id^=wpYourPluginName]:not(input:checkbox),input[id^=wpYourPluginName]:checkbox:checked");
        var $this = this;
        collection.each(function () {
            var name = this.name.substring(13, this.name.length-1);
            $this['options'][name] = this.value;
        });
        send_to_editor(this.generateShortCode());
        return false;
    }
}

var wpYourPluginAdmin = new wpYourPluginNameAdmin();

This JavaScript parses items from the form, formats a shortcode, and sends it to the editor! Now you can create an interface for your user, to allow to easily generate VALID shortcodes for you to parse.

63 thoughts on “WordPress 2.5 Shortcodes

  1. wow. Great article, it really summarizes the whole thing perfectly. Bookmarked!
    One thing i’m a bit confused about is send_to_editor(this.generateShortCode());

    Where is that defined? Part of the general wp admin js?

    • It is defined in wp-admin/js/media-upload.js, which is enqueued in:
      wp-admin/page-new.php
      wp-admin/post-new.php
      wp-admin/page.php
      wp-admin/post.php

      Basically, it’s enqueued on all write/edit pages.

  2. Brilliant article thanks! Was processing my own content using regex and string replacement. Finding this tidied up the code somewhat. Thanks for the tips on the admin panel as well!

  3. I just started playing with shortcode. I wrote a short function to display site url. It works fine with Post but it doesn’t work with Page at all. For instance, my shortcode is [url]. When put it in a page it shows [url] itself, instead of the site url.

    First I assumed that it works only for Post. But in this post of yours and you said “As you can see, shortcodes allow a user to put a code into a post or PAGE”. Did I do something wrong? or do I have to write extra code?

    Hope to hear from you soon.

    Cheers :)