Smashing Magazine - we smash you with the information that will make your life easier. really.
Mastering WordPress Shortcodes
Introduced in WordPress 2.5, shortcodes are powerful but still yet quite unknown WordPress functions. Imagine you could just type “adsense” to display an AdSense ad or “post_count” to instantly find out the number of posts on your blog.
WordPress shortcodes can do this and more and will definitely make your blogging life easier. In this article, we’ll show you how to create and use shortcodes, as well as provide killer ready-to-use WordPress shortcodes that will enhance your blogging experience.
[By the way, did you know there is a brand new Smashing Wordpress Book? Push WordPress past its limits!]
What Are Shortcodes?

Using shortcodes is very easy. To use one, create a new post (or edit an existing one), switch the editor to HTML mode and type a shortcode in brackets, such as:
[showcase]
It is also possible to use attributes with shortcodes. A shortcode with attributes would look something like this:
[showcase id="5"]
Shortcodes can also embed content, as shown here:
[url href="http://www.smashingmagazine.com"]Smashing Magazine[/url]
Shortcodes are handled by a set of functions introduced in WordPress 2.5 called the Shortcode API. When a post is saved, its content is parsed, and the shortcode API automatically transforms the shortcodes to perform the function they’re intended to perform.
Creating a Simple Shortcode
The thing to remember with shortcodes is that they’re very easy to create. If you know how to write a basic PHP function, then you already know how to create a WordPress shortcode. For our first one, let’s create the well-known “Hello, World” message.
- Open the functions.php file in your theme. If the file doesn’t exists, create it.
- First, we have to create a function to return the “Hello World” string. Paste this in your functions.php file:
function hello() { return 'Hello, World!'; } - Now that we have a function, we have to turn it into a shortcode. Thanks to the
add_shortcode()function, this is very easy to do. Paste this line after ourhello()function, then save and close the functions.php file:add_shortcode('hw', 'hello');The first parameter is the shortcode name, and the second is the function to be called.
- Now that the shortcode is created, we can use it in blog posts and on pages. To use it, simply switch the editor to HTML mode and type the following:
[hw]
You’re done! Of course, this is a very basic shortcode, but it is a good example of how easy it is to create one.
Creating Advanced Shortcodes
As mentioned, shortcodes can be used with attributes, which are very useful, for example, for passing arguments to functions. In this example, we’ll show you how to create a shortcode to display a URL, just as you would with the BBCodes that one uses on forums such as VBulletin and PHPBB.
- Open your functions.php file. Paste the following function in it:
function myUrl($atts, $content = null) { extract(shortcode_atts(array( "href" => 'http://' ), $atts)); return '<a href="'.$href.'">'.$content.'</a>'; } - Let’s turn the function into a shortcode:
add_shortcode("url", "myUrl"); - The shortcode is now created. You can use it on your posts and pages:
[url href="http://www.wprecipes.com"]WordPress recipes[/url]
When you save a post, the shortcode will display a link titled “WordPress recipes” and pointing to http://www.wprecipes.com.
Code explanation. To work properly, our shortcode function must handle two parameters: $atts and $content. $atts is the shortcode attribute(s). In this example, the attribute is called href and contains a link to a URL. $content is the content of the shortcode, embedded between the domain and sub-directory (i.e. between “www.example.com” and “/subdirectory”). As you can see from the code, we’ve given default values to $content and $atts.
Now that we know how to create and use shortcodes, let’s look at some killer ready-to-use shortcodes!
1. Create a “Send to Twitter” Shortcode

The problem. Seems that a lot of you enjoyed the “Send to Twitter” hack from my latest article on Smashing Magazine. I also really enjoyed that hack, but it has a drawback: if you paste the code to your single.php file, the “Send to Twitter” link will be visible on every post, which you may not want. It would be better to control this hack and be able to specify when to add it to a post. The solution is simple: a shortcode!
The solution. This shortcode is simple to create. Basically, we just get the code from the “Send to Twitter” hack and turn it into a PHP function. Paste the following code in the functions.php file in your theme:
function twitt() {
return '<div id="twitit"><a href="http://twitter.com/home?status=Currently reading '.get_permalink($post->ID).'" title="Click to send this page to Twitter!" target="_blank">Share on Twitter</a></div>';
}
add_shortcode('twitter', 'twitt');To use this shortcode, simply switch the editor to HTML mode and then type:
[twitter]
and a “Send to Twitter” link will appear where you placed the shortcode.
Source and related plug-ins:
2. Create a “Subscribe to RSS” Shortcode

The problem. You already know that a very good way to gain RSS subscribers is to display a nice-looking box that says something like “Subscribe to the RSS feed.” But once again, we don’t really want to hard-code something into our theme and lose control of the way it appears. In this hack, we’ll create a “Subscribe to RSS” shortcode. Display it in some places and not others, in posts or on pages, above or below the main content, it’s all up to you.
The solution. As usual, we create a function and then turn it into a shortcode. This code goes into your functions.php file. Don’t forget to replace the example feed URL with your own!
function subscribeRss() {
return '<div class="rss-box"><a href="http://feeds.feedburner.com/wprecipes">Enjoyed this post? Subscribe to my RSS feeds!</a></div>';
}
add_shortcode('subscribe', 'subscribeRss');Styling the box. You probably noticed the rss-box class that was added to the div element containing the link. This allows you to style the box the way you like. Here’s an example of some CSS styles you can apply to your “Subscribe to RSS” box. Simply paste it into the style.css file in your theme:
.rss-box{
background:#F2F8F2;
border:2px #D5E9D5 solid;
font-weight:bold;
padding:10px;
}3. Insert Google AdSense Anywhere

The problem. Most bloggers use Google AdSense. It is very easy to include AdSense code in a theme file such as sidebar.php. But successful online marketers know that people click more on ads that are embedded in the content itself.
The solution. To embed AdSense anywhere in your posts or pages, create a shortcode:
- Open the functions.php file in your theme and paste the following code. Don’t forget to modify the JavaScript code with your own AdSense code!
function showads() { return '<div id="adsense"><script type="text/javascript"><!-- google_ad_client = "pub-XXXXXXXXXXXXXX"; google_ad_slot = "4668915978"; google_ad_width = 468; google_ad_height = 60; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script></div>'; } add_shortcode('adsense', 'showads'); - Once you have saved functions.php, you can use the following shortcode to display AdSense anywhere on your posts and pages:
[adsense]
Note that our AdSense code is wrapped with an
adsensediv element, we can style it the way we want in our style.css file.
Code explanation. The above code is used simply to display AdSense ads. When the shortcode is inserted in a post, it returns an AdSense ad. It is pretty easy but also, you’ll agree, a real time-saver!
Sources:
4. Embed an RSS Reader

The problem. Many readers also seemed to enjoy the “8 RSS Hacks for WordPress” post published on Smashing Magazine recently. Now, let’s use our knowledge of both RSS and shortcodes to embed an RSS reader right in our posts and pages.
The solution. As usual, to apply this hack, simply paste the following code in your theme’s function.php file.
//This file is needed to be able to use the wp_rss() function.
include_once(ABSPATH.WPINC.'/rss.php');
function readRss($atts) {
extract(shortcode_atts(array(
"feed" => 'http://',
"num" => '1',
), $atts));
return wp_rss($feed, $num);
}
add_shortcode('rss', 'readRss');To use the shortcode, type in:
[rss feed="http://feeds.feedburner.com/wprecipes" num="5"]
The feed attribute is the feed URL to embed, and num is the number of items to display.
5. Get posts from WordPress Database with a Shortcode
The problem. Ever wished you could call a list of related posts directly in the WordPress editor? Sure, the “Related posts” plug-in can retrieve related posts for you, but with a shortcode you can easily get a list of any number of posts from a particular category.
The solution. As usual, paste this code in your functions.php file.
function sc_liste($atts, $content = null) {
extract(shortcode_atts(array(
"num" => '5',
"cat" => ''
), $atts));
global $post;
$myposts = get_posts('numberposts='.$num.'&order=DESC&orderby=post_date&category='.$cat);
$retour='<ul>';
foreach($myposts as $post) :
setup_postdata($post);
$retour.='<li><a href="'.get_permalink().'">'.the_title("","",false).'</a></li>';
endforeach;
$retour.='</ul> ';
return $retour;
}
add_shortcode("list", "sc_liste");To use it, simply paste the following in the WordPress editor, after switching to HTML mode:
[liste num="3" cat="1"]
This will display a list of three posts from the category with an ID of 1. If you don’t know how to get the ID of a specific category, an easy way is explained here.
Code explanation. After it has extracted the arguments and created the global variable $posts, the sc_liste() function uses the get_posts() function with the numberposts, order, orderby and category parameters to get the X most recent posts from category Y. Once done, posts are embedded in an unordered HTML list and returned to you.
Source:
6. Get the Last Image Attached to a Post
The problem. In WordPress, images are quite easy to manipulate. But why not make it even easier? Let’s look at a more complex shortcode, one that automatically gets the latest image attached to a post.
The solution. Open the functions.php file and paste the following code:
function sc_postimage($atts, $content = null) {
extract(shortcode_atts(array(
"size" => 'thumbnail',
"float" => 'none'
), $atts));
$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
foreach( $images as $imageID => $imagePost )
$fullimage = wp_get_attachment_image($imageID, $size, false);
$imagedata = wp_get_attachment_image_src($imageID, $size, false);
$width = ($imagedata[1]+2);
$height = ($imagedata[2]+2);
return '<div class="postimage" style="width: '.$width.'px; height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>';
}
add_shortcode("postimage", "sc_postimage");To use the shortcode, simply type the following in the editor, when in HTML mode:
[postimage size="" float="left"]
Code explanation. The sc_postimage() function first extracts the shortcode attributes. Then, it retrieves the image by using the get_children(), wp_get_attachment_image() and wp_get_attachment_image_src() WordPress functions. Once done, the image is returned and inserted in the post content.
Sources:
7. Adding Shortcodes to Sidebar Widgets

The problem. Even if you enjoyed this article, you may have felt a bit frustrated because, by default, WordPress doesn’t allow shortcode to be inserted into sidebar widgets. Thankfully, here’s a little trick to enhance WordPress functionality and allow shortcodes to be used in sidebar widgets.
The solution. One more piece of code to paste in your functions.php file:
add_filter('widget_text', 'do_shortcode');That’s all you need to allow shortcodes in sidebar widgets!
Code explanation. What we did here is quite simple: we added a filter on the widget_text() function to execute the do_shortcode() function, which uses the API to execute the shortcode. Thus, shortcodes are now enabled in sidebar widgets.
Sources:
WordPress Shortcodes Resources
- Shortcode API
The WordPress Codex page related to the shortcode API. - WordPress 2.5 shortcodes
Excellent shortcodes tutorial. - WordPress shortcode generator
The page is in French but provides a very useful and easy-to-use app to create shortcodes online. - Using Wordpress shortcode to create beautiful download boxes
Another great use of shortcodes: creating fancy “Download” boxes for your blog. - Easy way to advertise in WordPress using shortcodes
Great resource to manage and insert advertising on your blog, brought to you by WpEngineer. - Create a signature using WordPress shortcodes
Really simple but really cool: a shortcode to display a graphic signature on your blog. - How to: Use WordPress shortcodes with attributes
Concise tutorial on using shortcode attributes.
(al)
This guest post was written by Jean-Baptiste Jung, a 26-year-old blogger from Belgium, who blogs about WordPress at WpRecipes and about everything related to blogging and programming at Cats Who Code. You can stay in touch with Jean by following him on Twitter.
- 72 Comments
- 1
- 2
February 2nd, 2009 8:31 pmSome Of them I knew Already Some of them are not… Thanks for the info Jean!!
DKumar M.
- 3
February 2nd, 2009 8:32 pmA very useful tips. Thanks Jean!
- 4
February 2nd, 2009 9:37 pmanother smashing post!. :)
Now I am going to retheme my blog.. - 5
February 2nd, 2009 9:47 pmThis is an example of articles we need, not just lists and lists. Not that the lists are bad, but information is better.
Then again, we all have different requirements.
- 6
February 2nd, 2009 9:59 pmWow this is a great tip that I didn’t know about – thanks!! (Dugg.)
- 7
February 2nd, 2009 10:33 pma very good article! i’ll definitely gonna make shortcodes !
- 8
February 2nd, 2009 10:35 pmAgree with African Boy, less lists please and more articles like this. I actually learned stuff I didn’t know!
- 9
February 2nd, 2009 11:03 pmThank you!!!
- 10
February 2nd, 2009 11:06 pmwow… nice post… thanks…
- 11
February 2nd, 2009 11:35 pmGreat !!!
- 12
February 2nd, 2009 11:50 pmThis is great! More like this, please
(Running off to create a new wp theme…) - 13
February 2nd, 2009 11:57 pmVery useful and interesting article. Thanks a lot!
- 14
February 2nd, 2009 11:58 pmthis is so great! thanks for the detailed description!!
- 15
February 3rd, 2009 12:00 amGreat tutorial. The one on inserting the adsense will definitely be of great use to me.
- 16
February 3rd, 2009 12:59 amExcellent article. Clear, consice and easy to follow…exactly what the Dr ordered :-) Well done!
- 17
February 3rd, 2009 2:10 amI’ve already discovered the power of the functions.php-file and these shortcodes are another tool in my kit, thanks very much !
- 18
February 3rd, 2009 2:58 amWow, that’s great! Didn’t knew that feature existed. I really like the Embed Adsense Code in posts shortcode. It sure saves a lot of time… Thanks for sharing!
- 19
February 3rd, 2009 2:58 amI think I found a minor error.
In the 5th tip, where a post is retrieved directly from the database, the shortcode reads
[liste num="3" cat="1"],
but the code in functions.php that catches the shortcut is add_shortcode(”list”, “sc_liste”);so I guess the code you have to insert should read:
[list num="3" cat="1"]It’s just one character, but an important one, right ?
- 20
February 3rd, 2009 3:00 amGreat article! Thanks
- 21
February 3rd, 2009 3:12 amVery interesting hack!
I’ll use them to make my codex smaller end easier!Manu
manublog.org - 22
February 3rd, 2009 3:22 amAwesome !
WordPress is very suitable for light-scale web development for those people that not much in pure coding techniques like me >_<
- 23
February 3rd, 2009 3:37 amYahooo! very helpful…Tnx for sharing SM!
- 24
February 3rd, 2009 4:18 amExcellent article, found it through feedly´s twitter.
- 25
February 3rd, 2009 5:21 amwhat is de URL of the picture by ” 2. Create a “Subscribe to RSS” Shortcode”
- 26
February 3rd, 2009 5:33 amAwesome post. Please give us more of these helpful tutorials that show us more of what WordPress can do (and more of Jean-Baptiste’s genius!)
I agree with African Boy and Youri – list posts have nothing on posts as useful and informational this one :)
- 27
February 3rd, 2009 6:35 amSame question as mathiz’s;
What’s the url of the blog used for the screenshot at “Create a “Subscribe to RSS” Shortcode”? Looks like I design worth checking out.
- 28
February 3rd, 2009 6:42 amGreat list and great and useful information. A lot of thanks :)
- 29
February 3rd, 2009 6:53 amwow, this post is extremely useful for everybody who uses WordPress, thanks!! :)
- 30
February 3rd, 2009 8:26 amWow, we’ve been using Wordpress for years and never knew the process for doing this. Thanks for the great tip!
- 31
February 3rd, 2009 8:49 amAwesome article !!!
Really thanks :-)
- 32
February 3rd, 2009 9:53 amAWESOMENESS! bookmarked!
- 33
February 3rd, 2009 10:05 amI’m glad to see all theses nice comments, great to see you enjoyed the article! Thanks for your support!
- 34
February 3rd, 2009 11:39 amI was lately thinking about how to easily add images with lighboxes to posts… you just hit the jackpot… thanks for the amazing article :)
- 35
February 3rd, 2009 12:32 pmGood stuff here – I just converted my site to use Wordpress, and this functionality seems to offer a great amount of flexibility. I wasn’t aware that this existed at all, thanks!
- 36
February 3rd, 2009 12:56 pmgreat article, definitely going to come in handy
- 37
February 3rd, 2009 3:10 pmAwesome. i love the twitter shortcode. highly useful…
- 38
February 3rd, 2009 3:55 pmgood~!article
- 39
February 3rd, 2009 9:20 pmGreat! Can I use short codes in a comment?
- 40
February 3rd, 2009 10:37 pmThis would come much more handy with large chunks of random snippet insertions.
- 41
February 3rd, 2009 11:43 pmAWESOMENESS!
That’s I’ve been studying and trying to summarize.
Thanks for the tips. and hoping more informaiton for other shortcodes. - 42
February 4th, 2009 5:06 amSimply marvellous it’s going to help me so much with my new blog:
charlie-blog.com/media - 43
February 4th, 2009 7:44 amThanks, this post helped save me several hours of custom code on a Wordpress customization project.
- 44
February 4th, 2009 8:51 amThis is a great article. I didn’t know that Wordpress had such a thing built in. This is definitely useful. Thanks for the tips!
- 45
February 4th, 2009 1:05 pmThis just made my day.
- 46
February 4th, 2009 11:02 pm假如有中文就更完美了
- 47
February 5th, 2009 2:27 amOh My ~楼上那个王韬~我好像认识你~
- 48
February 5th, 2009 1:16 pmvery helpful article for webmaster who are using wordpress . Very Very thank you.
- 49
February 6th, 2009 12:10 amreally awesome article. thanks for sharing
- 50
February 7th, 2009 7:24 pmso powerful tips.
- 51
February 8th, 2009 9:49 amGreat post. I like a lot of functionality but tons of plugins slow down loading. This one tip replaces several plugins and gives me a great direction to go in.
- 52
February 8th, 2009 4:53 pmImpressive tutorial, or should i say tutorials to learn how to use wordpress in an advanced way, for that i thank, a lot.
- 53
February 10th, 2009 6:34 pmhi all
on “step” 6. why it takes the last image?! how can I do to take the first image?!?!
BR,
Cassiano - 54
February 11th, 2009 9:26 pmThanks, this makes easy to maintain word press
- 55
February 11th, 2009 10:39 pmHi,
It is really neat tutorial, i have to admit :)
One question though. In the 3rd heading you’ve put the following in the code box:
<script type=”text/javascript”
src=”http://media.smashingmagazine.com/cdn_smash/images/mastering-wordpress-shortcodes/http://pagead2.googlesyndication.com/pagead/show_ads.js”>
</script>Is this an AdSense hack I’m not aware of or you just deliberately wanted to mess up the AdSense code which is against the AdSense ToS?
- 56
February 12th, 2009 5:00 amWow, this is awesome.
I guess there is always new stuff to learn, thanks for sharing.
- 57
February 19th, 2009 7:47 amGreat article, thanks. Also does anyone know what plugin is being used to display the code here? I’d really like to get that rolling.
- 58
March 31st, 2009 3:20 pmThanks for a great article. I wrote a plugin called ‘MapPress’ that lets you insert Google Maps (as shortcodes), directly from the WordPress editor.
I stumbled on your article when my 71-year-old Mom asked me ‘what is a shortcode?’…
- 59
May 1st, 2009 2:20 pmGreat article but I was a bit frutrated with “Embed an RSS reader”. It really dont works for me (Wordpress 2.7.0).
For each try I made, it’s every time the same result in my page: “an error has occured the feed is probably down, try again later”.
An idea ? - 60
May 6th, 2009 10:04 amGreat post, I’m really impressed about such things you can do with a bit of code
- 61
May 20th, 2009 9:24 amHow about:
add_filter( 'comment_text', 'do_shortcode' );adding shortcodes to comments!
- 62
June 22nd, 2009 1:21 pmthanks for great tutorial
- 63
July 12th, 2009 10:54 pmYou’re a great site! Thanks
- 64
July 17th, 2009 1:33 amThe “Embed an RSS reader” shortcode is buggy (
wp_rss()performsechonot areturn). Fix it Fix it [fr] with the second block code. - 65
August 31st, 2009 9:45 amThere’s a problem with the “Get posts from WordPress Database with a Shortcode” example.
It causes all comments added to the final post in the list to appear in the article you added the list to.
Is there a way to fix this problem?
- 66
September 2nd, 2009 5:07 amExcellent Article !!!!!!
- 67
October 12th, 2009 4:40 pmTabea…. Salam kenal dari Manado – Indonesia. Good n thanks,-
- 68
October 27th, 2009 9:48 pmThanks , this is awesome , made my life 10 years longer ;)
- 69
November 16th, 2009 4:08 amThanks for the valuable article on shortcodes. Your introduction and application of this very powerful Wordpress tool has come in handy on several occasions throughout my “apprenticeship” with Wordpress.
R
- 70
December 1st, 2009 4:26 amGreat Article,thank you
- 71
December 19th, 2009 6:21 amAwesome writeup, but i have a question…
all the shortcodes i define myself end up giving me triplicate results on my pages
for example if i create an adsense short code and embed it in my blog i get 3 adsense blocks… but if i use a short code defined in one of the plugins i’m using it works great (only 1 instance of the results)…
Would you happen to have any insight on this issue ?
Thank you for the great writeup!
- 72
January 18th, 2010 4:25 amYou guys rule!
- 00
There are no trackbacks at this time. If you are interested in leaving a trackback, please use this URL.
Leave a Comment
Make sure you enter the * required information where indicated. Please also rate the article as it will help us decide future content and posts. Comments are moderated – and rel="nofollow" is in use. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!
Interact
Popular
- 100 Wordpress Themes
- Photoshop Tutorials
- Fantastic Wallpapers
- 40+ Excellent Freefonts
- Dual-Screen Wallpapers
- Wordpress Themes for 2009
- Illustrator Tutorials
- Incredible Free Icon Sets
- High-Quality Free Fonts
- 30 Scripts For Galleries
- Photoshop Text Effects
- Useful Icon Sets
- Web Design Trends
- iPhone Wallpapers
- Before Launching a Website
- CSS Layouts And Templates
- Photoshop Actions
- Stunning Pictures and Photos
- Fantastic HDR Pictures
- Logo Design Tutorials
- Free Design Templates
- 10 Mistakes In Logo Design
- Photoshop Custom Shapes
- 40 Creative Design Layouts
- 8 Layout Solutions
- 53 CSS Techniques
- Photography Techniques
- Black & White Photography
- Styling Design Elements
- CSS-Based Forms
- 50 jQuery Techniques
- 50 Portfolio Websites
- 50 CSS Techniques
- Creative Logo Designs
- Desktop Wallpapers
- 25 Open Source Mac Apps
- 50 Free Icon Sets
- lovely-css: a grid-based CSS framework - http://bit.ly/ayA0wb
- How The CSS Selector nth-child Works - http://bit.ly/cgPMqe
- 33 New High Quality Adobe Illustrator Tutorials - http://bit.ly/bTgFbu
- How to Drastically Improve Your Designs - http://bit.ly/a9L1sb
- A Quick Look at Mobile Web Designs - http://bit.ly/9TCWCG
- How to Test your JavaScript Code with QUnit - http://bit.ly/da853c
- jQuery 1.4 API Cheat Sheet - http://bit.ly/5zYYnE


Great post, thanks! I’m really only just starting to realise the power of WordPress :)