"In this article, you will be given a detailed explanation of WordPress’ shortcode API and learn how to create a shortcode… the right way. You will then be shown some useful examples of more advanced shortcodes and how to code your own custom variations! Ready to add a new skill to your bag of tricks? Let’s get started!
What are shortcodes?
Shortcodes were introduced in WordPress 2.5. To put things simply, a shortcode is a shortcut. They are WordPress-specific pieces of code that allow you to save time and do things that would otherwise require technical knowledge and possibly large amounts of code. By adding shortcodes to your themes or plugins, you could make using it so much easier and intuitive. You could, for example, have a shortcode[most_popular_post]
that when typed out exactly like that would display the most popular post on your WordPress site. If you wanted to do this manually, you would have to write some HTML code, as well as have to manually change it as and when the popularity of posts changed. A shortcode takes away the need for this, and simplifies things for you. A shortcode is a WordPress-specific code that lets you do nifty things with very little effort. Shortcodes can embed files or create objects that would normally require lots of complicated, ugly code in just one line. Shortcode = shortcut. -WordPress.com
How are shortcodes created?
Shortcodes are created using the WordPress shortcode API. they work a lot like WordPress filters. You have to define a handler function that parses the shortcode and returns some output. You then register the shortcode using theadd_shortcut()
function. A shortcut handler function accepts up to three arguments, listed below:$atts
: An array of any shortcode attributes$content
: Any content that the shortcode may enclose$code
: The shortcode name (used usually when the same handler is used for multiple shortcode
wptuts
.[wptuts]
$atts
= array()$content
= null
[wptuts]Lorem ipsum dolor sit amet[/wptuts]
$atts
= array()$content
= Lorem ipsum dolor sit amet
[wptuts id='555' name='some name']
$atts
= array(‘id’ => ’555′, ‘name’ => ‘some name’)$content
= null
[wptuts id='555']Lorem ipsum dolor sit amet[/wptuts]
$atts
= array(‘id’ => ’555′)$content
= Lorem ipsum dolor sit amet
Note: Shortcodes are self enclosing. Therefore,[wptuts]
is the same as[wptuts /]
. You only need to use opening and closing shortcode tags when theres is content in between.
Create your first shortcode
Now that you have learned the basics of the shortcode API, you can go ahead and create your first shortcode. I will be using the TwentyEleven theme included with WordPress, and screenshots will reflect this, but you can use any theme of your choice, or even write a plugin.To begin, open up the
functions.php
file of the theme, and add this line of code to the top:include 'shortcodes.php';Your
functions.php
should look like this:Next, create the file that you just referenced –
shortcodes.php
. To make things easier, all our shortcodes will be in this file. To begin, we will be creating a very simple shortcode that generates a link to Tweet the post URL. Create a function wptuts_first_shortcode()
and fill it in with this code:function wptuts_first_shortcode($atts, $content=null){ $post_url = get_permalink($post->ID); $post_title = get_the_title($post->ID); $tweet = '<a href="http://twitter.com/home/?status=Read ' . $post_title . ' at ' . $post_url . '">Share on Twitter</a>'; return $tweet; } add_shortcode('twitter', 'wptuts_first_shortcode');Your first shortcode is now ready to go! You can try it out by typing
[twitter]
into a post. Here’s an example of your output:More Shortcodes
Now that you’ve created a basic shortcode, we can go ahead and create some more shortcodes that use the different arguments like$atts
and $content
. Embed a YouTube video
A YouTube embed shortcode serves a great purpose since embedding a video requires coding knowledge; with a shortcode, the effor requires is significantly reduced. Plus this technique can be applied to make shortcodes that can embed other videos or even media like pictures or audio files. Paste this code intoshortcodes.php
:function wptuts_youtube($atts, $content=null){ extract(shortcode_atts( array('id' => ''), $atts)); $return = $content; if($content) $return .= "<br /><br />"; $return .= '<iframe width="560" height="349" src="http://www.youtube.com/embed/' . $id . '" frameborder="0" allowfullscreen></iframe>'; return $return; } add_shortcode('youtube', 'wptuts_youtube');Notice what we’re doing here. The shortcode has a single attribute: the video ID (which can be taken from the URL of a youtube video). The function
shortcode_atts()(
works a lot like wp_parse_args()
. It parses the attributes and uses the specified array as one of defaults. The returned value is an array with all the keys from the first array, replaced with the correspomding values in the $atts
array, if present. If the content between the shortcode tags isn;t empty, we display it, add a couple of line breaks and embed the video. Try it! The code I used was:[youtube id="_ggWarwhv9M" ]Check out this video![/youtube]Here’s the result:
Display the most recent post from the blog
Another example of a great shortcode is one that displays the most recent blog post. The advantage of this is that every time a new post comes out, no manual updating is required. Here’s the code:function wptuts_recentpost($atts, $content=null){ $getpost = get_posts( array('number' => 1) ); $getpost = $getpost[0]; $return = $getpost->post_title . "<br />" . $getpost->post_excerpt . "…"; $return .= "<br /><a href='" . get_permalink($getpost->ID) . "'><em>read more →</em></a>"; return $return; } add_shortcode('newestpost', 'wptuts_recentpost');What we do is use the
get_posts()
function to retrieve the most recent post and display the title, excerpt and a link to the post. The shortcode has no attributes, but you could, as an example, add attributes to display posts from a particular category or display a user-defined number of newest posts. You can try the shortcode out with this code:<strong><em>Check out our latest post:</em></strong> <br /> [newestpost]Here’s what it looks like:
Wrapping it all up
There are a few more things that may come in handy as you delve into more advanced shortcode development.- Removing shortcodes: Shortcodes can be removed using the
remove_shortcode()
function. Usage isremove_shortcode($shorcodename)
. You can also remove all shortcodes by using the functionremove_all_shortcodes()
- Applying the shortcode filter: By default, WordPress scans the post content for shortcodes and applies them. However, there are two cases in which you may want to explicitly tell WordPress to parse shortcodes in a string. For this, you need the
do_shortcode($content)
function. The first case is for nested shortcodes – just usedo_shortcode
on the$content
passed to you i.e. instead ofreturn $content;
, usereturn do_shortcode($content)
. This will ensure that nested shortcodes are processed. The second scenario where you may want this is when you want non-post content to be scanned for shortcodes. For example, if you want the content of widgets to be parsed, you can just add this filter:add_filter('widget_text', 'do_shortcode');
(source: Shortcodes In Widgets)