WordPress shortcodes are used frequently in plugins and themes as a way to achieve extra functionality, without the need to modify template files. You just type the shortcode word right into your post. Some plugins and themes use them to add event calendars, some for making announcements, while others use them for inserting contact forms.

Simply, WP shortcodes are awesome.

However, what if you’re a theme / plugin developer wishing to use them for your next great product, but you have no idea where to start? We’re going to fix that in this tutorial.

1 – Overview – Exactly Where We are Going

We will start out by looking at the basic ways that we can use WP shortcodes, then we will move onto some more advanced tricks. After the usage sections, I’m going to show you some examples of real-world shortcodes, followed by even more ideas / references of what you could do with them.

2 – Getting Into the Basics

The first you thing you should always do when working with something WordPress, is check the WordPress Codex. It’s a great reference and starting point.

Shortcodes, like just about everything else in WordPress, can be created in the functions.php file, or from within your plugin file if you’re developing a plugin.

Let’s start simple by making a shortcode that we can use to add additional styles to some text.

1
2
3
4
function extra_style_shortcode( $atts, $content = null ) {
   return '<span style="color: blue; text-decoration: underline;">' . $content . '</span>';
}
add_shortcode('extra-style', 'extra_style_shortcode');

This is a very simple example that serves almost no purpose, but easily illustrates the basics of shortcode creation. It allows us to do something like this in our WP posts/pages:

[extra-style]Hello World![/extra-style]

and have it outputted like this:

Hello World!

So what’s happening? It’s simple, we’re simply telling WordPress to put all of the text inside of the [ ] . . . [/ ] into a variable called $content, then outputting $content inside of a span tag that has some simple inline styling applied to it.

Okay, that was easy, now let’s get into something a little more complex. This time we’ll give the ability to define the color of the text using attributes.

1
2
3
4
5
6
7
function extra_style_shortcode( $atts, $content = null ) {
    extract(shortcode_atts(array(
		"color" => 'blue',
	), $atts));   
   return '<span style="color: ' . $color . '; text-decoration: underline;">' . $content . '</span>';
}
add_shortcode('extra-style', 'extra_style_shortcode');

Now we can do this:

[extra-style color=red]Hello World![/extra-style]

and we’ll see: Hello World!

or:

[extra-style color=orange]Hello World![/extra-style]

and we’ll see: Hello World!.

This example uses this bit of code

    extract(shortcode_atts(array(
		"color" => 'blue',
	), $atts));

to extract the information inputted by the user for the variable color. We have also defined a default color of blue in case no color is defined.

Again, this example is pretty much useless, but its simplicity makes it very easy to understand.

Let’s get just a little bit more complex before moving on.

1
2
3
4
5
6
7
8
9
function extra_style_shortcode( $atts, $content = null ) {
    extract(shortcode_atts(array(
	"color" => 'blue',
        "size" => '14px',
        "padding" => '0px',
	), $atts));   
   return '<span style="color: ' . $color . '; padding: ' . $padding . '; font-size: ' . $size . '; text-decoration: underline;">' . $content . '</span>';
}
add_shortcode('extra-style', 'extra_style_shortcode');

By using a shortcode like this within a block of text:

[extra-style color=purple size=18px padding=5px]Hello World![/extra-style]

we could see something like this:

Elementum odio? Sed, Hello World! proin pulvinar eros nascetur, massa urna aliquam turpis elit, adipiscing mauris montes ac, vel lacus placerat in adipiscing ridiculus rhoncus.

Well that’s enough of the pointless examples; let’s look at some real shortcode examples.

3 – Making an Information Box

This shortcode example will let you include a nice little message box at the top of your post to help catch readers’ eyes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function box_shortcode( $atts, $content = null )
{
    extract( shortcode_atts( array(
      'color' => 'yellow',
      'size' => 'medium',
      ), $atts ) );
 
      return '
		<style type="text/css">
		.shortcode_box {
			padding: 2px 4px;
			border: 1px solid #ccc;
		}
		.yellow {
			background: #ffd149;
			color: #666;
		}
		.blue {
			background: #a0c5ef;
			color: #333;
		}
		.gray {
			background: #f0f0f0;
			color: #333;
		}
		</style>
 
      <div class="shortcode_box ' . $size . ' ' .  $color . '">' . $content . '</div>';
 
}
add_shortcode('box', 'box_shortcode');

Now we can use our “box” shortcode to produce something like this

This is a message box with important information you should read.

by using this shortcode:

[box color=yellow]This is a message box with important information you should read.[/box]

By changing the color variable, we can have different colors of boxes:

This is a message box with important information you should read.
This is a message box with important information you should read.

With a little more CSS, we could also control the size of the box, but I’ll leave that to you.

4 – Create a Download Button

The process for creating a download button is very similar to creating a message box: we simplu wrap the content of the button inside of a div with some special CSS3 styles applied to it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function button_shortcode( $atts, $content = null )
{
    extract( shortcode_atts( array(
      'color' => 'blue',
      'size' => 'medium',
      ), $atts ) );
 
      return '
		<style type="text/css">
		.shortcode_button {
			padding: 2px 8px;
			border: 1px solid #ccc;
			border-radius: 10px;
			-webkit-border-radius: 10px;
			-moz-border-radius: 10px;
		}
		.black {
			background: #ffd149;
			background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#636363), to(#332F2F));
			background: -moz-linear-gradient(19% 75% 90deg,#332F2F, #636363);
			color: #f0f0f0;
			border-top-color: #1c1c1c;
			border-left-color: #1c1c1c;
			border-right-color: #525252;
			border-bottom-color: #525252;
		}
		.blue {
			background: #a0c5ef;
			background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#508BC7), to(#203F75));
			background: -moz-linear-gradient(19% 75% 90deg,#203F75, #508BC7);
			color: #f0f0f0;
			border-top-color: #023778;
			border-left-color: #023778;
			border-right-color: #26609e;
			border-bottom-color: #26609e;
		}
 
		.large	{
			width: 200px;
		}
		.medium	{
			width: 120px;
		}
		.small	{
			width: 80px;
		}
		</style>
 
      <div class="shortcode_button ' . $size . ' ' .  $color . '">' . $content . '</div>';
 
}
add_shortcode('button', 'button_shortcode');

We can display our button by using:

[button color=black size=medium]<a href="#">Download</a>[/button]

which will give us:

In order to control the size or color of the button, all we have to do is create a CSS class with the same name as the value we input for our size / color variables. For example, if we do size=large in our shortcode, we need a CSS class called large in our stylesheet. You can see I have included extra styles in my above example to illustrate some possible options.

5 – Buttons and Boxes Together

Shortcodes are great because they also let us combine them to a result like:

Porta ultricies. Amet odio amet, pellentesque elementum adipiscing sagittis enim, eu, proin placerat sed pid cum? Dictumst turpis integer. Adipiscing, porttitor scelerisque! Lorem turpis porttitor.

Integer in, odio mattis ac! Nascetur augue odio in risus, arcu nunc, phasellus ultrices lectus velit, et tincidunt tristique. Integer vel pulvinar purus magnis.

by using a shortcode like:

[box color=blue]Porta ultricies. Amet odio amet, pellentesque elementum adipiscing sagittis enim, eu, proin placerat sed pid cum? Dictumst turpis integer. Adipiscing, porttitor scelerisque! Lorem turpis porttitor.
 
Integer in, odio mattis ac! Nascetur augue odio in risus, arcu nunc, phasellus ultrices lectus velit, et tincidunt tristique. Integer vel pulvinar purus magnis.
 
[button color=black size=small]<a href="#">Download[/button][/box]

There is one small hitch, though. By default, WordPress does not allow you to embed shortcodes within other shortcodes. In order to get around that, we have to add a line to our functions.php or main plugin file:

add_filter('the_content', 'do_shortcode');

This will make WordPress process both sets of shortcodes.

6 – Show Related Posts

This is a really handy shortcode we can use to display a list of posts related to the current post by comparing tags.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function related_posts_shortcode( $atts ) {
	extract(shortcode_atts(array(
	    'limit' => '5',
	), $atts));
 
	global $wpdb, $post, $table_prefix;
 
	if ($post->ID) {
		$retval = '<ul>';
 		// Get tags
		$tags = wp_get_post_tags($post->ID);
		$tagsarray = array();
		foreach ($tags as $tag) {
			$tagsarray[] = $tag->term_id;
		}
		$tagslist = implode(',', $tagsarray);
 
		// Do the query
		$q = "SELECT p.*, count(tr.object_id) as count
			FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id  = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
				AND p.post_status = 'publish'
				AND p.post_date_gmt < NOW()
 			GROUP BY tr.object_id
			ORDER BY count DESC, p.post_date_gmt DESC
			LIMIT $limit;";
 
		$related = $wpdb->get_results($q);
 		if ( $related ) {
			foreach($related as $r) {
				$retval .= '
	<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>
';
			}
		} else {
			$retval .= '
	<li>No related posts found</li>
';
		}
		$retval .= '</ul>
';
		return $retval;
	}
	return;
}
add_shortcode('related_posts', 'related_posts_shortcode');

We can show the related posts by using:

[related_posts]

Credit goes to Blue Anvil for this shortcode.

7 – Drop Caps With a Shortcode

Drop caps are pretty and make your articles look really nice. They can really add some nice detail to post and make your site stand out above the rest.

1
2
3
4
5
6
function dropcap($atts, $content = null) {
	return '
<div class="dropcap">'.$content.'</div>
;';
}
add_shortcode('dropcap', 'dropcap');

The CSS:

1
2
3
4
5
6
7
.dropcap {
display:block;
float:left;
font-size:50px;
line-height:40px;
margin:0 5px 0 0;
}

Use it with:

[dropcap]M[/dropcap]auris ut lectus erat. In ...

Credit for this shortcode goes to TutToaster.

8 – Custom Post Type Query

Let’s say that you have set up a custom post type called News and you wish to display all posts inside that custom post type on a page called Articles. You could do it with the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function news_shortcode()
{
	//The Query
	query_posts('post_type=news');
	//The Loop
	if ( have_posts() ) : while ( have_posts() ) : the_post();
		echo	'<h3><a href="'; echo the_permalink(); echo '">'; echo the_title(); echo '</a></h3>';
		echo the_excerpt();
	endwhile; else:
	endif;
 
	//Reset Query
	wp_reset_query();
}
add_shortcode('news', 'news_shortcode');

Then display the news posts on your Articles page by using this shortcode:

[news]

9 – Display Posts from Category on Page

Very similar to the shortcode example above, we can also display limited number of posts from within a particular category using a shortcode like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function category_shortcode( $atts )
{
extract(shortcode_atts(array(
	    'limit' => '5',
            'category' => '',
	), $atts));
	//The Query
	query_posts('category=' . $id . 'posts_per_page=' . $limit);
	//The Loop
	if ( have_posts() ) : while ( have_posts() ) : the_post();
		echo	'<h3><a href="'; echo the_permalink(); echo '">'; echo the_title(); echo '</a></h3>';
		echo the_excerpt();
	endwhile; else:
	endif;
 
	//Reset Query
	wp_reset_query();
}
add_shortcode('category', 'category_shortcode');

You can list the posts using:

[category id=# limit=5]

Just replace # with the ID of the category you wish to display.

10 – Great Examples of Other Possible Shortcodes

I’ve shown you a few examples, both of my own and other’s creation, now let me give you even more examples of awesome things you could do.

Joen Asmussen of NoScope.com created a really nifty little shortcode to make a Google PDF Viewer.

Check it out here

Jean Baptiste, of WP-Recipes created a shortcode to display a “ReTweet” or “TweetMeme” buttons in your posts. Find it here.

Justin Tadlock made a great plugin that turns all (or most) WordPress template tags into shortcodes so that they can be used within the post editor. Download the Plugin.

A few weeks ago I wrote a shortcode plugin of my own (sorry, couldn’t leave myself out!). It’s a shortcode utility plugin that allows you to insert a variety of message boxes and web buttons via shortcodes (similar to some of the examples I’ve used above). Check out WP Utility Shortcodes.

11 – Some More Ideas

  • Use shortcodes for displaying contact forms
  • use shortcodes for displaying a Google map
  • Shortcodes to display author bios
  • A shortcode that outputs all of your social network info
  • Shortcodes for image galleries
  • Shortcodes for jQuery image sliders

Have you seen any other interesting uses of shortcodes? Do you make use of them in your site already?

Enjoy this post? You should follow me on Twitter!