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.

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 theadd_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.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 thefunctions.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:

  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 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:

  • An error has occurred; the feed is probably down. Try again later.

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:
  1. WordPress: Création de shortcode avancé
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() andwp_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 post
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 thewidget_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)

Mobile Web HandbookFixing technical issues on mobile is annoying. That’s why we’ve
teamed up with Peter-Paul Koch to create The Mobile Web
Handbook
, a new practical guide to deal with common front-end
challenges on mobile, effectively. Get the book now.

EssentialsShortcodesTechniques (WP)

↑ Back to topTweet itShare on Facebook

Jean-Baptiste Jung

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.

Related Articles

118

Rapid Front-End Prototyping With WordPress

118

A Detailed Guide To WordPress Custom Page Templates

118

How To Use Autoloading And A Plugin Container In WordPress Plugins

Mastering WordPress Shortcodes

Shortcodes and Sidebars

Can I use a shortcode or an auto-embedded URL in a sidebar
widget?
Ordinarily, WordPress doesn’t check sidebar text for autoembed
URLs and shortcodes. For example, if you add a Text
widget (page 166) and put a Flickr URL in it, that URL will appear
in your sidebar as ordinary text, not as an image preview.
If you use WordPress.com, you need to live with this restriction.
If you’re on a self-hosted site, there’s a fairly easy workaround,
but you need to be familiar with theme editing, an advanced
topic explored in Part 4.
The solution is to add two commands (shown on page 500) to
a file called functions.php. These commands tell WordPress to
process widget text in the same way that it processes the text
in a post or page—in other words, to check for auto-embedded
URLs and shortcodes. Using this technique, you can put tiny
videos, slideshows, galleries, and more in your sidebar without
relying on a specialized widget.

Shortcodes and Sidebars

Shortcodes

More Shortcodes
Shortcodes are special instructions you put in your post or page. Like an autoembedded
URL, a shortcode tells WordPress to insert something in the current
location. But auto-embeds are limited to a relatively small set of known websites,
while shortcodes let you add a much broader range of media.
To use a shortcode, you put a predetermined code inside square brackets. For example,
the following shortcode takes all the pictures attached to a post and combines
them into a picture gallery:
An image gallery will show up here:

You’ll take a much closer look at galleries in the next section. For now, the important
thing to understand is that, when you add a shortcode to a page or post, WordPress
inserts something out of the ordinary.
Shortcodes always have the same syntax—each one consists of a bit of text wrapped
in square brackets. In fact, the instruction you learned about in the previous
section is actually a shortcode that tells WordPress to examine a web address and
embed the appropriate content.

NOTE You can type shortcodes into the visual editor (the Visual tab) or the HTML editor (the Text tab). Either
way, WordPress recognizes the code by its square brackets.

The truly neat part about shortcodes is that they’re extensible. If you’re ambitious
and you run a self-hosted WordPress site, you can create your own shortcodes
(technically, it’s all about editing the functions.php file, as described on page 500).
Even better, a clever plug-in developer can create shortcodes that let you display
additional types of content, including contact forms, documents, maps, charts, ads,
a view counter, and a PayPal donation link.

If you run a self-hosted WordPress site, you start with the shortcodes:

TIP If you run a self-hosted site, you can add the extra shortcodes that WordPress.com sites get by installing
the handy Jetpack plug-in

Shortcodes

The [embed] Shortcode

Some WordPress aficionados write auto-embedded URLs differently from the earlier
example. They add a special code before and after the URL, like this:

Here, the web address is the same, but it has an http://%20code%20at%20the%20beginning%20ofbrthe%20URL%20and%20a%20matching%20 code at the end. This line of code produces the
same effect as in the previous example—WordPress replaces the URL with the appropriate
embedded content, provided that it recognizes the URL.

The main reason you’d use the

The height and width attributes don’t always give you the effect you expect. It’s best
to think of them as requests—requests that WordPress honors according to its own
intricate (and slightly obscure) sizing rules. Here’s a rundown of what takes place:

• If you don’t specify any size information, WordPress allows the embedded
content to grow until it reaches its full size or hits the boundaries of your layout.
For example, if you embed post content inside a 600-pixel-wide column, your
embedded picture will grow to be 600 pixels wide (and however tall it needs
to be to preserve the picture’s proper shape).

• If you specify the width and height attributes, you override WordPress’s ordinary
behavior. For example, you can specify a size to shrink a tall-and-skinny photo
that would otherwise grow bigger than you want it to be. And if the media
sharing site you use automatically shrinks your content, you may be able to use
the width and height attributes to force it bigger. (See the box on this page for
a full discussion of this often-perplexing issue.)

• You can use either the width or height attribute on its own. For example, you can
scale down a piece of content using a smaller width and let WordPress choose
the height automatically to match the original aspect ratio.

• WordPress doesn’t let you stretch embedded content out of shape. For example,
if you assign a height and width to a picture that don’t match its aspect ratio,
WordPress follows the most restrictive dimension and sizes the other to match.

• Different themes and plug-ins can tinker with the style rules that size the elements
in your layout, including embedded content. Unfortunately, the interplay
between the embedded content, WordPress, and your theme is complex.
Sometimes, despite your best efforts, embedded content will refuse your
resizing demands.

Sizing Quirks with Embedded Content

I embedded a Flickr picture, but it turned out way smaller
than I expected!
Some media services replace the full-size content you think
you’re embedding with a smaller-size version that they think
will better suit your site. This sleight of hand has a point—it’s
done to save bandwidth and reduce the time it takes your
page to load. For example, Flickr pictures can be quite big. By
handing you a smaller thumbnail (typically, a picture that’s
just 320 pixels wide), Flickr saves you from wasting pixels and
time. However, that also means the picture that appears in
your web page may be smaller than you expect.
You can solve this problem, to a certain extent, using the
http://%20code%20with%20the%20width%20attribute.%20But%20there’s%20a%20catch.brThe%20width%20attribute%20has%20no%20effect%20unless%20you%20use%20a%20size%20that’sbrbig%20enough%20to%20force%20Flickr%20to%20give%20you%20a%20bigger%20thumbnail.%20Forbra%20standard%20picture%20in%20portrait%20orientation,%20that%20width%20needs%20tobrbe%20700%20pixels%20or%20more.br[embed%20width=700]…
This is somewhat counterintuitive, because many themes have
less than 700 pixels of width to accommodate your picture.
Twenty Twelve, for instance, has a column width of 625 pixels.
However, this attribute still has the desired effect. It forces
Flickr to return a larger-sized thumbnail, which your theme
then scales down slightly to fit your layout.
Besides being confusing, this process leaves some notable
gaps. What if you want a picture that’s wider than 320 pixels
but narrower than 625 pixels? Or what if you want a picture
to grow beyond the size of your layout? There’s no easy fix
for these issues without getting your hands dirty. If you have
a self-hosted site, you can avoid the auto-embed feature
altogether, and copy the raw HTML markup that media sharing
services like Flickr provide. Just remember to paste the markup
in the Text tab (page 178), not the Visual tab. Or, for more
control—and much more complexity—you can muck around
with the CSS style rules that control the layout of your site
(Chapter 13). Both approaches can create problems that are
more aggravating than minor size issues. For most folks, the
best choice is to accept the quirks of the auto-embed feature
and let WordPress handle the heavy lifting.

The [embed] Shortcode