How to Create Your Own WordPress Shortcodes

WordPress doesn’t normally allow you to add PHP code to pages or posts. That’s for the best; you don’t want clients to discover the power of the unlink function! However, you can create custom functions which are executed when a shortcode is encountered within the post text.

Simple shortcodes

Shortcode functions can be added to plugin code or your theme’s functions.php file. If it’s the latter, I’d recommend creating a separate shortcodes.php file, then adding include('shortcodes.php'); to functions.php.

Here’s a basic “Hello World” example:


function HelloWorldShortcode() {
	return '<p>Hello World!</p>';
}
add_shortcode('helloworld', 'HelloWorldShortcode');

Enter [helloworld] somewhere within a page or post to output the result of the HelloWorldShortcode() function.

Parameterized shortcodes

The following shortcode function generates a page hierarchy sitemap. Three optional parameters can be passed: a title, the ID of the resulting ul list, and a depth value indicating the number of page navigation levels.


function GenerateSitemap($params = array()) {

	// default parameters
	extract(shortcode_atts(array(
		'title' => 'Site map',
		'id' => 'sitemap',
	    'depth' => 2
	), $params));

	// create sitemap
	$sitemap = wp_list_pages("title_li=&depth=$depth&sort_column=menu_order&echo=0");
	if ($sitemap != '') {
		$sitemap =
			($title == '' ? '' : "<h2>$title</h2>") .
			'<ul' . ($id == '' ? '' : " id="$id"") . ">$sitemap</ul>";
	}

	return $sitemap;
}
add_shortcode('sitemap', 'GenerateSitemap');

A custom sitemap can be added to any page using a shortcode such as [sitemap id='deepmap',depth=5].

BB code shortcode

The final way to add shortcodes uses [bbcode]BB code syntax[/bbcode]:


function StyleText($params, $content = null) {

	// default parameters
	extract(shortcode_atts(array(
		'style' => ''
	), $params));

  return
	'<span' .
	($style == '' ? '' : " style="$style"") .
	">$content</span>";
}
add_shortcode('format','StyleText');

This function allows the author to embed CSS styles within their article, e.g. [format style="font-size:1.5em;color:#f00;">Important![/format]. Perhaps that’s not such a great idea!…

Have you seen any interesting uses for shortcodes within WordPress projects?

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Webstergroup

    For a church website we use [SeniorPastor] [YouthPastor] etc. to place the name into pages and posts. This allows for name changes at various positions in the church without having to do a search and replace in the database. We do have an admin panel where the names of the replaceable positions are entered.

  • http://www.reich-consulting.net/ coffee_ninja

    Greart article! WordPress has great documentation but it’s sometimes very hard to wade through… and trying to read and follow the source code? Don’t get me started :) Thanks for simplifying one of WordPress’s many extension points.

  • Anonymous

    I’ve used shortcode to include content from other areas of the site. So you can. Do something like [include type="movies" category="horror" content="list"] or [include type="movies" category="horror" content="147"] or whatever. If the content attribute is numeric, I modify my custom query within the shortcode function to grab a specific post. If the content attribute is list, summary or gallery I output a loop of all posts with the specified custom post type and category in different layouts… a simple linked list, a summary list which includes a featured image thumbnail and excerpt, or a gallery view which is an array of linked thumbnail images.

  • http://www.satya-weblog.com/ satya prakash

    Cool concepts and tricks

  • tacitus

    If you want to embed HTML but don’t want to mess around with PHP code, then you might want to have a look at the Embedder plugin:

    http://wordpress.org/extend/plugins/embedder/

    (Yes, full, disclosure, I am the author — but it is free, no strings!)

    You can even add parameters (called embed attributes) and default values directly into the embedded HTML without any need for writing PHP. (Though you can still create a PHP function just like an ordinary shortcode if you want to — or even a combination of both!).

    The next version of the plugin (due soon) will include a new shortcode parser (for shortcodes defined with Embedder) that solves some annoying bugs with WordPress shortcodes (for example, try sticking two shortcodes right next to each other and see what happens!).

    Plenty of examples and documentation available too.