WordPress Shortcodes: A how to by example

I love the WordPress shortcode api. I’m willing to stand on a roof and scream it. It makes so many aspects of developing a WordPress site so much easier. It allows you to add dynamic information to any post, page, and with a single line text widget. How easy you ask? Let’s look at some examples so I can show you just how easy it is to use.

A shortcode for this year

Sometimes you just want to include the year inline and there’s no reason you should have to change the blog posts every time you want to do it. Here’s a quick shortcode for the year.

function show_current_year(){
	return date('Y');
}
add_shortcode('show_current_year', 'show_current_year');

Just that easy. As you can see there are a few components to a basic short code. The first is a function that returns what we want the shortcode to return and the second is a call to add_shortcode with the first parameters being what we want the shortcode to be and the second is the function we want that shortcode to call.

A custom links list shortcode

So that last one was pretty easy. Maybe we should try something a little harder, like adding an unordered list of links that uses each links image. This time we also add an attribute to allow us to limit it to a specific category.

function show_bookmark_image_list($atts){
    extract(shortcode_atts(array(
    'catagory_name' => false
    ), $atts));
    if ( $catagory_name == false )
        $bookmarks = get_bookmarks();
    else
        $bookmarks = get_bookmarks("catagory_name=$catagory_name");
    ob_start();
    echo "<ul class='link-image-list'>";
    foreach($bookmarks as $bookmark){
        echo "<li><a href='".esc_url($bookmark->link_url) ."'><img src='".esc_url($bookmark->link_image)."' /></a></li>";
    }   
    echo "</ul>";
    $list = ob_get_clean();
    return $list;
}
add_shortcode('show_bookmark_image_list', 'show_bookmark_image_list');

This time we added an attribute called Catagegory_name that we can then retrieve using the shortcode_atts function that also allows us to set a default incase no attribute is set. We then go through the list of bookmarks that we retrieve and echo out the results. Since we want our shortcode function to return the data, we wrap our echo is an output buffer. I prefer to use output buffers because it allows me to use echo (and makes the code more readable in my opinion), but you can also use string concoction and return the string if you want.

Most Recent Tweet

This was removed in August 2013 since it relied upon a non deprecated twitter api

Using Shortcodes inside Text/html widgets

Text widgets can be simple and are great for creating small blocks of content that you can place any where your theme allows. This simple hack will allow you to use shortcodes inside your text widgets. Just add the following single line to your theme’s functions.php file.

add_filter('widget_text', 'do_shortcode');

If you want to download and use these three simple shortcodes and enable the use of shortcodes in your text widgets, download this file, remove the .txt at the end of the file, upload it to your plugins folder, and activate the simple shortcodes plugin.

Those three simple sample shortcodes for WordPress should give you a bit of a base to create your own. What are your favorite shortcodes? What’s a shortcode that you wish existed? Comment below and let me know. Also let me know if there is any part of my code that you don’t understand, and I’ll try to help you understand it.

UPDATE

I’ve added two more twitter shortcodes. You can also download all of my shortcodes and follow along to the development of them on google code.

Published by

Aaron Jorbin

Polyhistoric man of the web. Currently Technical Architect on the Conde Nast Platform Team and a WordPress Core Committer, he works to improve developer happiness and is dedicated to making the internet usable and enjoyable by everyone. He's probably wearing a bow tie right now.

18 thoughts on “WordPress Shortcodes: A how to by example”

    1. That’s correct. By default, shortcodes aren’t parsed in template unless you wrap them like:
      < ?php echo do_shortcode('[twitter_status screenname='aaronjorbin' ]'); ?>

  1. Hey Aaron,

    Informative stuff, thanks.

    I have an issue you may be able to shed light upon: I am attempting to use the Sideblog or Minipost2 plugin with [wpaudio] shortcodes from the wpaudio plugin to allow the client user to add audio to the sidebar. Using a text widget parses the shortcode of course but I can’t give the user admin privileges to update a text widget.

    The do_shortcode technique you’ve pointed out works in my template files but that of course won’t allow the client to add new wpaudio shortcodes to the sidebar.

    My question — something I’ve spent the whole day searching for and puzzling over — is how to apply do_shortcode to the output of , < ?php sideblog('listen'); ?>for example?

    I’ve tried to modify the technique to parse shortcodes in text widgets by writing add_filter(‘widget_sideblog’, ‘do_shortcode’); to the functions.php but that seems to have no affect.

    I’ve been mucking around in both plugin’s php files to try and mimick the codex’s

    function caption_shortcode( $atts, $content = null ) {
    return '' . do_shortcode($content) . '';
    }

    but can’t find a clear way to include that and am not even sure that is the appropriate approach.

    I hope that you might have some ideas to the correct way to proceed.

    Much thanks in advance,
    Owen

    1. Hey Owen,

      First I would check the code of the plugin and see if the sideblog function has a filter that you can add do_shortcode too. If not, It’s a bit of a hack, but You might want to try something along the lines of (note: untested):

      add_filter('my_sideblog', 'do_shortcode');
      ob_start();
      sideblog('listen');
      $sideblog = ob_get_clean();
      echo apply_filter('my_sideblog', $sideblog);

      I hope that helps.

  2. I’m noticing that my custom theme doesn’t support short codes because I never get them to work directly from the content page. They work if I call them directly from the php code. Do you know what I can do to fix the problem?

  3. Thanks for sharing

    Is there any extensions for [else] eg

    [loggedin]
    logged in text
    [else]
    logged out text
    [/loggedin]

    Is there any easy way to do that?

    TIA

    1. I think your best bet for a solution like that would be to do two seperate shortcodes a [loggedin] and [notloggedin] one that only prints the information inside of it if the user is either logged in or not logged in.

  4. hello,

    I wrote my plugin using shortcode APIs, everything works fine when looking at articles; when looking at the “category view” the shortcodes are either not rendered or stripped of HTML tags.

    Is this the normal behaviour of the “category view” or do I miss something?

    Thanks

    1. If your category page is using the_excerpt rather then the_content, then shortcodes aren’t being processed on that page. Adding the following to your plugin should fix it, but will cause all shortcodes to get run and could cause your excerpts to become a lot longer then you intend.

      add_filter('the_excerpt', 'do_shortcode', 11);

      1. Thanks.
        That solves part of the problem, if the theme does not process shortcodes at all.
        There is also a second part to the problem, some theme does process the shortcodes, but then shows excerpts after stripping HTML tags. My plugin uses an iframe, if you strip the HTML tags that is broken.
        Some theme allows configuring all this (which tags are stripped and which are preserved, for instance) other dont.
        I whish wordpress would allow to configure this at the site appearance options rather than leaving it to the them to make it configurable or setting it in stones.

  5. This is such a terrific resource that you are supplying and you give it away totally free. I like seeing blogs that realize the importance of offering a useful resource for absolutely free. I really loved reading your post ;) Many thanks

  6. Great intro to short codes! Love it! Have just tested out the twitter shortcode example & quite pleased to have it working! Not sure if am asking for the moon on a stick, but is it possible to tweek this code a little?
    What am seeing is that the image grabbed from twitter although aligned left it doesn;t float properly and the text starts at the bottom of the pic, making it look a little untidy.
    Also, can it be made to ‘parse’ links in a tweet? Seems to parse @mentions into links ok, so puzzled why it doesn’t do links.
    Thanks again for the great intro to shortcodes!

    1. You can use css on the twitter_shortcode_image class to align the link. You can also run the make_clickable function on $tweet_display before returning it to make all the uris clickable.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>