PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

How to Create Your Own WordPress Shortcodes

Note: This article was originally published at Planet PHP on 11 November 2010.
Planet PHP

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 aoHello Worlda example:

function HelloWorldShortcode() { return '

Hello World!

'; } 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 == '' ? '' : "

$title

") . '
    $sitemap
"; } 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 '$content"; } 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!a

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