Mastering WordPress Shortcodes

Advertisement

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.

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.

  1. Open the functions.php file in your theme. If the file doesn’t exists, create it.
  2. 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!';
    }
  3. 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 our hello() 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.

  4. 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.

  1. 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>';
    }
  2. Let’s turn the function into a shortcode:
    add_shortcode("url", "myUrl");
  3. 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.com1.

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 Magazine2. 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.

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:

  1. 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');
  2. 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 adsense div 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 WordPress6” 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 here7.

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:

  1. WordPress: Création de shortcode avancé8

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:

  1. WordPress Shortcode: easily display the last image attached to post9

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

(al)

Footnotes

  1. 1 http://www.wprecipes.com
  2. 2 http://www.smashingmagazine.com/2009/01/07/10-killer-wordpress-hacks/
  3. 3 http://www.wprecipes.com/how-to-create-a-send-this-to-twitter-button
  4. 4 http://alexking.org/blog/2007/05/07/twitter-tools-10
  5. 5 http://www.wprecipes.com/how-to-embed-adsense-anywhere-on-your-posts
  6. 6 http://www.smashingmagazine.com/2008/12/02/10-useful-rss-hacks-for-wordpress/
  7. 7 http://www.wprecipes.com/how-to-find-wordpress-category-id
  8. 8 http://www.webinventif.fr/wordpress-creation-de-shortcode-avance/
  9. 9 http://www.wprecipes.com/wordpress-shortcode-easily-display-the-last-image-attached-to-post
  10. 10 http://www.wprecipes.com/how-to-add-shortcodes-in-sidebar-widgets
  11. 11 http://englishmike.net/2008/07/07/wordpress-quick-tips-3adding-a-shortcode-to-a-sidebar-widget/
  12. 12 http://codex.wordpress.org/Shortcode_API
  13. 13 http://xavisys.com/2008/04/wordpress-25-shortcodes/
  14. 14 http://www.webinventif.fr/generateur-de-shortcode-et-de-boutons-pour-wordpress/
  15. 15 http://www.subzane.com/2009/01/07/wordpress-shortcode-create-beautiful-download-boxes/
  16. 16 http://wpengineer.com/easy-way-for-advertisement-in-wordpress/
  17. 17 http://nice2all.com/2008/12/17/wordpress-short-codes/
  18. 18 http://www.wprecipes.com/how-to-use-wordpress-shortcodes-with-attributes

↑ Back to top Tweet itShare on Facebook

This guest post was written by Jean-Baptiste Jung, a 28-year-old blogger from Belgium, who blogs about Web Development on Cats Who Code, about WordPress at WpRecipes and about blogging on Cats Who Blog . You can stay in touch with Jean by following him on Twitter.

Advertisement
  1. 1

    This has just what I needed to get going thanks.

    1
  2. 102

    How hard would it be to create a short code that requires you to use a 2 part short code. Example: I would like to avoid the copy/paste method that I’m using to create a 2 column table set. If I could do [side1]…[/side1] [side2]…[.side2] and have them combine each other into 1 table that would be awesome, but it would only work if they are both used.
    http://inertubetv.splendidangst.com/archives/79

    That’s the table layouts I have manually created in HTML in the post.

    1
  3. 203

    Shortcodes are not working in my WordPress(3.2.1) installation. It just prints the code itself. Anyone has any idea?

    1
    • 304

      function sc_postimage($postID)
      {
      $args = array(
      ‘numberposts’ => 500,
      ‘order’=> ‘ASC’,
      ‘post_mime_type’ => ‘image’,
      ‘post_parent’ => $postID,
      ‘post_status’ => null,
      “size” => ‘thumbnail’,
      ‘post_type’ => ‘attachment’,
      “float” => ‘none’
      );

      $attachments = get_children( $args );

      //print_r($attachments);

      if ($attachments) {
      $i=0;
      ?>

      ID, ‘thumbnail’ ) ? wp_get_attachment_image_src( $attachment->ID, ‘thumbnail’ ) : wp_get_attachment_image_src( $attachment->ID, ‘full’ );

      ?>

      <a href="”>
      <?php if($i==0){echo "”;}
      $i++; ?>

      <?php echo 'ID ).'” class=”current” style=”width: ‘.$width.’px; height: ‘.$height.’px; float: ‘.$float.';”>';

      ?>

      <?php
      if($i==3)
      {
      echo "”;
      $i=0;
      }
      }
      echo “”;
      }
      }

      add_shortcode(“postimage”, “sc_postimage”);

      html tag table tr td not working in form

      1
  4. 405

    About example 5), there is an important fix:

    You should add “wp_reset_query();” inbetween line 13 and 14 (before “return $retour;”).

    Otherwise you mess with the values (date, categories etc) of the main post, they will be overriden by the posts from the shortcode. Depending on your specific theme, this can have unwanted results, wrong values in sidebars, footers, etc.

    You probably want to go back to the main loop, and that’s exactly what “wp_reset_query();” does.

    1
  5. 506

    Rad. I dislike WordPress slightly less after reading this. We (WP + me) have a love/hate relationship.

    1
  6. 607

    thanks a lot.. I was breaking my head from last few hours.. and here I found the exact solution.

    1
  7. 708

    Amazing post. I love it. Thanks for sharing with us. I hope to see more

    1
  8. 809

    Thank you. What a nice explanation of Shortcodes and how they work. I had no idea they were so simple to create and implement. You have inspired me to experiment. Thanks!

    0
  9. 910

    Great Man!!!
    Now I’m going to create my own shortcode…..

    0
  10. 1011

    Is there a shortcode for username that you can place on a page? This would be for a Welcome page.

    Caps

    0
  11. 1112

    Get page from WordPress Database with a Shortcode

    function pagedata($atts, $content = null) {
    extract(shortcode_atts(array(
    “id” => ‘1’
    ), $atts));

    query_posts( ‘page_id=’.$id);
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    $retour=”.get_the_title().”;
    $retour.=’‘;
    $retour.=’ ‘;

    endwhile;
    endif;
    wp_reset_query();
    return $retour;

    }
    add_shortcode(“page”, “pagedata”);

    0
  12. 1213

    The adsense shortcode worked like a charm…Thanks Great Article BTW!

    0
  13. 1314

    Hi there,

    Im wanting to create a photo blog theme, i want to use short codes for inserting images into posts rather than the user just adding images straight to the editor.

    What I want to do also is wrap the image inside some custom html, this is just some divs and spans.

    so basically the output looks like:

    Description goes here.

    I’m guessing the shortcode would look something like:

    [img src=”path to image”]Image Description[/img]

    Then the user can just keep adding this shortcode to the editor over and over:

    [img src=”path to image”]Me at the beach[/img]
    [img src=”path to image”]Friends at dinner[/img]
    [img src=”path to image”]Vacation in New Zealand[/img]

    Is that possible with shortcodes?

    0
  14. 1415

    I found this very difficult. I coded the “twitter” example and it worked well. However when I removed the “twitter” code from the functions file, the “twitter” example hung around like a bad smell. Where does the code reside when this happens. The reverse also occurred. I coded the “Hello world” example but made some sort of mistake. However even when I corrected the mistake it could not be made to work. I then coded remove_shortcode(‘hw’) and a corrected version of “Hello world”. It then worked.

    0
  15. 1516

    The adsense code is not working anymore!

    0
  16. 1617

    Great Tutorial ! Thanks

    0
  17. 1718

    Hi,
    I would like to know how to add shortcodes to wp_head. More exactly, I use a shortcode [y] that displays the year and I add it to the title of the page, so NOT in the body of the page, within the text field. After I publish the page, in the title added to the content the year is displayed well, but in the meta title it doesn’t show up, there can be seen the code [y], just like in the page source. There is possible to make shortcodes working in the head area? Maybe using an add_filter in functions.php?
    Thanks in advance for your help!

    0

↑ Back to top