When an editor adds a WordPress [shortcode] to a post or page, it’s replaced by the returned output of a handler function within a plug-in or the theme’s functions.php file. Let’s create a simple example:

// create a styled button
function ContactButton($params, $content = null) {

		'url' => '/contact-us',
		'type' => 'style1'
	), $params));

		'<a href="' . $url . '" class="button ' . $type. '">' . ucwords($content) . '</a>';


When the following code is encountered in page or post:

[button]contact us today[/button]

it’ll be translated to:

<a href="/contact-us" class="button style1">Contact Us Today</a>

The editor’s job is made far easier and they don’t need to worry about learning HTML. Let’s look at another example which creates a simple callout box:

// callout box
function CalloutBox($params, $content = null) {

		'type' => 'style1'
	), $params));
		'<aside class="callout ' . $type . '">' . $content . '</aside>';


But what if our editor wants to insert a button inside their callout box?…

[callout]For more information [button]contact us today[/button][/callout]

As it stands, the current code will fail. The CalloutBox function is called first but the inner [button] will not be translated accordingly.

The key function for fixing the problem is do_shortcode() — it applies WordPress’s shortcode filter to any content. In this case, we want to allow the editor to add a [button] within our [callout] so we’d change modify the return statement of CalloutBox accordingly:

	'<aside class="callout ' . $type . '">' . 
	do_shortcode($content) . 

The nested code above will now work as expected. However, the editor wouldn’t be permitted to nest a [callout] inside a [button]. It’s flexibility such as this which makes WordPress a joy to use — version 3.3 is available now.

Tags: PHP, shortcodes, WordPress
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler

  • http://runyoncanyon-losangeles.com Andrew

    When you think about the amount of css you need to write, shortcodes don’t seem so short. :-)

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.