Skip to main content

How to Create Your Own WordPress Shortcodes

By Craig Buckler



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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
		'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
		'style' => ''
	), $params));

	'<span' .
	($style == '' ? '' : " style="$style"") .

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?

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 created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.