If you’ve been reading this blog for any length of time, you’ve noticed my penchant for asides — brief digressions in which I explain a term, offer advice, or explain why I’m doing something a certain way.
Until yesterday, I was doing that via raw HTML, by adding a div tag and assigning it to the CSS class “aside,” which is defined in my theme’s style.css file:
<div class="aside">This content will appear as an aside.</div>
And that makes the text above look like this:
Well, I’m just as lazy as the next guy, and just as careless, too. So sometimes I was forgetting to close that div, or was misspelling it, or otherwise making a general mess by typing a simple div tag.
Which got me to thinking: Why not make a WordPress shortcode plugin, to abbreviate and simplify this repetitive task?
Making your own shortcode is an excellent way to learn the basics of writing WordPress plugins. And once you get the hang of it, you’ll find WordPress plugin authoring isn’t all that hard to do, yet will make you infinitely more marketable as a Web developer.
An Overview Of WordPress Shortcodes
As the name implies, a WordPress shortcode is a way to use a simple, short directive to apply formatting, or append code, to a WordPress post or page.
More often than not, shortcodes are provided as part of a larger plugin solution.
For example, I use SyntaxHighlighter Evolved for code markup.
By typing a simple shortcode — [vbnet][/vbnet], [js][/js], [php][/php], etc. — I can quickly apply SyntaxHighlighter to my code samples. SyntaxHighlighter Evolved will also do me the favor of converting HTML entities, so I don’t have to do that by hand.
For example, this:
[php] $foo = '<p>soup & sandwich</p>'; echo $foo; [php]
Becomes this:
$foo = '<p>soup & sandwich</p>'; echo $foo;
There are a number of plugins and strategies meant to prevent this from happening. I’ve tried a few and found them problematic. That’s why I pretty much edit text exclusively in the HTML editor. It’s just easier and more reliable.
Of course, if you don’t usually blog things that require special coding, sticking with the visual editor is fine. It handles shortcodes without incident, provided what you put inside the shortcode isn’t raw HTML.
Another example of how a shortcode can be used to add elements or affect style is WordPress’s built-in [caption] shortcode.
If you look at your post in the WordPress HTML editor, after uploading and adding a captioned photo, the code block that contains the photo will look something like this:
[caption id="attachment_5042" align="alignnone" width="604"]<a href="http://dougv.com/wp-content/uploads/2012/03/Blake_Lively_2011_Shankbone_1500-e1427838103448.jpg"><img src="http://dougv.com/wp-content/uploads/2012/03/Blake_Lively_2011_Shankbone_1500-e1427838103448.jpg" alt="Blake Lively" width="1453" height="1449" class="size-full wp-image-5042" /></a>Blake Lively At The TIME 100 Gala, 26 April 2011. Photo credit: David Shankbone via Wikimedia Commons[/caption]
As you can see, the [caption] shortcode takes a series of attribute arguments — id, align, width and caption — and wraps itself around the selected image.
When the post renders on the screen, the HTML produced looks like this:
<div id="attachment_5042" class="wp-caption alignnone" style="width: 614px"<a href="http://dougv.com/wp-content/uploads/2012/03/Blake_Lively_2011_Shankbone_1500-e1427838103448.jpg"><img src="http://dougv.com/wp-content/uploads/2012/03/Blake_Lively_2011_Shankbone_1500-e1427838103448.jpg" alt="Blake Lively" width="1453" height="1449" class="size-full wp-image-5042" /></a><p class="wp-caption-text">Blake Lively At The TIME 100 Gala, 26 April 2011. Photo credit: David Shankbone via Wikimedia Commons</p></div>
So, the [caption] shortcode:
- outputs a containing div;
- assigns the id of the caption as the id of that containing div;
- adds the wp-caption CSS class to the div;
- assigns the align attribute as a CSS class for that div;
- sets the width of the image, plus 10 pixels, as the width of the caption container (to allow for 5 px padding left and right); and
- places the value of the caption attribute into a paragraph element, which is made a child element of the caption div.
The final product looks like this:

Obviously, a WordPress shortcode is a very powerful way to render formulaic content. Any time you find yourself repetitively writing the same HTML or text, over and over again, you should consider making a shortcode, especially if hand-coding that pattern is time-consuming or accident-prone.
An Overview Of WordPress Plugins
A WordPress plugin is basically a way to intercept any of the many events that take place when working with WordPress, and to get WordPress to either alter how it goes about that task, add additional steps, or not do what it would normally do.
Usually, a plugin watches for when a post or page is created, and either adds some content, changes content somehow, or performs additional tasks related to the content being created or changed.
For example, there are plugins that will post a tweet any time you create a new post. Other plugins will optimize your post’s search engine indexing; figure out which previous posts are related to this post and hyperlink to them; automatically tag your post with relevant terms; etc.
Some plugins don’t deal with posts at all. There are plugins that extend and improve the built-in user management system; work with special post types; provide shopping carts or forums; or even fundamentally change the functionality of WordPress.
A plugin might leverage one event in the WordPress lifecycle, or several events. It might do one thing — such as our plugin — or scores of things.
Really, the sky is the limit. By design, WordPress is very extensible, which is a big part of the reason why it’s so popular.
“There’s a plugin for that” is pretty much cliche when it comes to WordPress. But in those cases when there isn’t a plugin for that, you can make one yourself.
Your First WordPress Plugin In Three Easy Steps
So let’s make a really basic WordPress shortcode plugin — one that will apply a specific style to the text it contains.
First, let’s put together the CSS for our [aside] shortcode. We’ll call that CSS style, appropriately, .aside:
div.aside { padding: 25px 50px; background: #efe; font-size: 12px !important; line-height: 150%; text-align: justify; }
Put this CSS block in your theme’s style.css file.
Next, we need to fire up a text editor — Notepad or TextEdit will do fine; I use Notepad++ — and write the plugin that will provide our shortcode functionality.
If your text editor saves files in UTF-8, for example, when you activate a plugin, WordPress will report an error along the lines of:
The plugin generated X characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
To fix that, set your text editor to save files in ANSI encoding, copy and paste your plugin code into new text files, replace your wrongly encoded plugin files with those new files, and reinstall the plugins.
According to the WordPress Codex, in order to create a plugin, we first need to provide a PHP comment block that contains some metadata: The name of our plugin, some author and version information, plus a description.
If we don’t include this metadata, we can’t manage it in the Plugins area of the WordPress admin section. So let’s do that first.
/* Plugin Name: Aside Shortcode Plugin URI: http://dougv.com/2012/03/16/making-a-simple-wordpress-shortcode-plugin/ Description: A simple plugin that adds an "aside" shortcode to WordPress Version: 1.0 Author: Doug Vanderweide Author URI: http://dougv.com License: GPL3 */
With that out of the way, we can actually create our shortcode. We do that with a simple PHP function.
Our function should be named something other than what we want to use as a shortcode. In other words, I want to use [aside] as my shortcode; so I don’t want to call this function aside. Instead, I’ll name it aside_shortcode.
function aside_shortcode($atts, $content = null) { return '<div class="aside">' . $content . '</div>'; }
Note the two arguments. I’ll discuss those shortly.
As you can see, our function simply adds a div tag, with the aside class, around the content contained inside our shortcode tags.
We now need to give our shortcode a name, and tell it to use this function when it finds those shortcode tags. That’s handled via the add_shortcode function, which is built into WordPress:
add_shortcode('aside', 'aside_shortcode');
So, here’s what our entire plugin PHP file looks like:
<?php /* Plugin Name: Aside Shortcode Plugin URI: http://dougv.com/2012/03/16/making-a-simple-wordpress-shortcode-plugin/ Description: A simple plugin that adds an "aside" shortcode to WordPress Version: 1.0 Author: Doug Vanderweide Author URI: http://dougv.com License: GPL3 */ /* Copyright 2012 Doug Vanderweide This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ function aside_shortcode($atts, $content = null) { return '<div class="aside">' . $content . '</div>'; } add_shortcode('aside', 'aside_shortcode'); ?>
We just save this file with the name aside_shortcode.php.
Final step: Install and activate the plugin.
We can do that one of two ways:
- Use FTP to create an aside_shortcut folder inside our wp-content/plugins folder; then upload our aside_shortcut.php file into that new folder.
- Add aside_shortcut.php to a ZIP file; then use the Add New feature, under Plugins in the WordPress admin section, to upload and automatically create the appropriate directory.
With the plugin uploaded, we just need to go to the Plugins page in the WordPress admin section and activate it.
Congratulations! You’re officially a WordPress developer.
More On WordPress Shortcodes
I previously noted that aside_shortcode took two arguments: $attrs and $content.
(Technically, a shortcode function can take a third argument, $code, which is a reference to the shortcode name itself. But do me a favor and forget about that. There’s a reason for it, but it’s very specialized and almost always inapplicable.)
If I were writing a shortcode that had attributes / arguments — for example, such as this:
[caption id="attachment_4535" align="alignnone" width="585" caption="Blake Lively At The TIME 100 Gala, 26 April 2011. Photo credit: Flynet © 2011"]
— then, when I wrote my shortcode handler function, $attrs would be an associative array of all the attributes that were added to my shortcode:
$attrs['id'] = 'attachment_4535'; $attrs['align'] = 'alignnone'; $attrs['width'] = 585; $attrs['caption'] = 'Blake Lively At The TIME 100 Gala, 26 April 2011. Photo credit: Flynet © 2011';
In our [aside] shortcode, we’re not using attributes / arguments, so $attrs is a zero-length array.
But suppose you want to write a shortcode that can apply any of several CSS classes to a selection of text. Let’s call that shortcode “styler,” and let’s suppose it takes an argument with the name “class,” which will be the CSS class you want to assign to the enclosed text, via a span tag.
We can change our shortcode function to handle that:
function styler_shortcode($atts, $content = null) { return '<span class="' . $attrs['class'] . '">' . $content . '</span>'; } add_shortcode('styler', 'styler_shortcode');
So, if we had this in our post content:
Four score and [styler class="big"]seven years[/styler] ago, our fathers [styler class="small"]brought[/styler] forth on this [styler class="green"]continent[/styler] ...
it would render this HTML:
Four score and <span class="big">seven years</span> ago, our fathers <span class="small">brought</span> forth on this <span class="green">continent</span> ...
Again, you’d just need to add the relevant CSS classes to your theme’s style.css file, and those styles would be applied to the rendered text.
Actually, you could write your plugin in a way that it either adds the relevant CSS to your WordPress installation’s head, or references a stylesheet specific to the plugin; or even provide an admin settings panel that lets end users define styles.
That’s more advanced stuff, so I won’t get into it here. Just know that again, the possibilities are endless.
By now, you’ve probably figured out that $content represents all the text that appears between opening and closing shortcode tags.
In other words, given this:
[caption id="attachment_4535" align="alignnone" width="585" caption="Blake Lively At The TIME 100 Gala, 26 April 2011. Photo credit: Flynet © 2011"]<img src="http://dougv.com/wp-content/uploads/2012/03/Blake_Lively_FNP_EW_0186946.jpg" alt="Blake Lively" title="The TIME 100 Gala: TIME'S 100 Most Influential People In The World" width="585" height="840" class="size-full wp-image-4535" />[/caption]
$content is:
<img src="http://dougv.com/wp-content/uploads/2012/03/Blake_Lively_FNP_EW_0186946.jpg" alt="Blake Lively" title="The TIME 100 Gala: TIME'S 100 Most Influential People In The World" width="585" height="840" class="size-full wp-image-4535" />
The default value of $content is null because in some cases, we may want to write a shortcode that simply renders some pre-determined content on the screen.
For example, suppose you have a couple standard lines of text you use to conclude a post:
Copyright © 2012 <a href="http://www.twitter.com/#!/dougvdotcom/">Doug Vanderweide</a>. I distribute code under the <a href="http://www.gnu.org/licenses/gpl-3.0.html">GNU GPL version 3</a>. I herd u liek mudkipz.
Since these lines are static, we can call them via a very simple shortcode. We’ll call that shortcode “kicker,” which will take an ID attribute of 1, 2 or 3, for whichever line we want to output; if no such attribute is specified, the third line will be used.
Thus, our shortcode function would be:
function kicker_shortcode($atts, $content = null) { switch($attrs['id']) { case 1: $out = 'Copyright © 2012 <a href="http://www.twitter.com/#!/dougvdotcom/">Doug Vanderweide</a>.'; break; case 2: $out = 'I distribute code under the <a href="http://www.gnu.org/licenses/gpl-3.0.html">GNU GPL version 3</a>.'; break; default: $out = 'I herd u liek mudkipz.'; } return $out; } add_shortcode('kicker', 'kicker_shortcode');
After installation, we call that shortcode in our posts or pages thus:
Thanks for reading! [kicker id="1"]
As in, no need for content / containing shortcode tags. Wherever we put that single shortcode tag, there will be our output:
Thanks for reading! Copyright © 2012 <a href="http://www.twitter.com/#!/dougvdotcom/">Doug Vanderweide</a>.
This code on github: https://github.com/dougvdotcom/wordpress_shortcode
All links in this post on delicious: http://delicious.com/dougvdotcom/making-a-simple-wordpress-shortcode-plugin
Thanks, that helped me get started.
Dear Doug,
Good morning!
We have a doubt about shortcodes as follows: Is it possible to have a webpage developed based on shortcopes that functions well at the visual admin? Or in other words: Is it possible to visualize the page without the html codes?
Thanks and bests regards.
Rogerio
@Rogerio: Yes. A number of plugins use a shortcode, on a single, otherwise blank post or page, to render content.
Awesome! Saved me loads of time putting repeating content at the bottom of multiple pages. Thanks a lot!