Getting Started with WordPress Shortcodes & Sample Snippets


By

WordPress shortcodes were introduced in 2.5 and help you to create macro codes to use within your content. If you think about it, this is a great way to create something like a dynamic ad spot or a call-to-action button in your posts.

If we use the call-to-action example, you could add something like this to your blog post to show the button and then edit the output in your templates functions.php file, which we’ll get to in a minute.

[button]

To customize the button, we could add something like the following:

[button type="twitter"]

Or, to make it even better, we could use an enclosing shortcode:

[button type="twitter"]Follow me on Twitter![/button]

With some imagination, you soon realize the potential of shortcodes and what can be done with them. In this article, I’ll show you how to create and use these three different types of shortcodes, and then I’ll show off some ready-to-use shortcodes to use on your own WordPress site.

Creating a Self-Closing Shortcode

The simplest shortcode is the self-closing one. We will create a simple link to a Twitter account and then add it to a blog post.

All the code goes in functions.php, which is located in /wp-content/themes/your-theme/. If you don’t have one, create it and put the code in it.

<?php 
function button_shortcode() {
    return '<a href="http://twitter.com/filipstefansson" class="twitter-button">Follow me on Twitter!</a>"';
}
add_shortcode('button', 'button_shortcode'); 
?>

Usage:

[button]

Simply using the add_shortcode() function, we can link any PHP function to our shortcode. In this simple example, all we do is return a link to the Twitter account, but let’s take this a step further and add some parameters.

Creating a Self-Closing Shortcode with Parameters

Shortcode has support for parameters, which lets us customize the output. In this example, we have two different buttons, so we have to define what button we want to show.

<?php
function button_shortcode($type) {
    extract(shortcode_atts(array(
        'type' => 'type'
    ), $type));
    
    // check what type the user entered
    switch ($type) {
        case 'twitter':
            return '<a href="http://twitter.com/filipstefansson" class="twitter-button">Follw me on Twitter!</a>';
            break;
        case 'rss':
            return '<a href="http://example.com/rss" class="rss-button">Subscribe to the feed!</a>'
            break;
    }
}
add_shortcode('button', 'button_shortcode');
?>

Now you can choose what button to display by defining type in your shortcode.

[button type="twitter"]
[button type="rss"]

This is great. But what if we wanted to change the text? We could keep on adding shortcode types like [button type="twitter-2"] and so on, but that’s not very dynamic. Let’s see how to do this the right way.

Creating an Enclosing Shortcode

The enclosing shortcode allows you to embed content within your shortcode, just like BBCode if you’ve ever used that.

<?php
function button_shortcode( $attr, $content = null ) {
    return '<a href="http://twitter.com/filipstefansson" class="twitter-button">' . $content . '</a>';
}
add_shortcode('button', 'button_shortcode');
?>

To use this shortcode, you embed the text you want to use like this:

[button]Follow me on Twitter![/button]

To make this button even better, we could add parameters as we did in the previous example. Let’s add two parameters this time, one for the Twitter username and one for the button style.

Then we can have different types of buttons and choose what Twitter account we want to link the button to.

<?php
function button_shortcode( $atts, $content = null ) {
   extract( shortcode_atts( array(
      'account' => 'account',
      'style' => 'style'
      ), $atts ) );

   return '<a href="http://twitter.com/' . esc_attr($account) . '" class="twitter-button ' . esc_attr($style) . '">' . $content . '</a>';
}
add_shortcode('button', 'button_shortcode');
?>

Usage:

[button account="filipstefansson" style="simple"]Follow me on Twitter![/button]
// Result: &lt;a href="http://twitter.com/filipstefansson" class="twitter-button simple">Follow me on Twitter!&lt;/a>

Now we have a customizable button that we can link to any Twitter account. As I’m sure you understand, you can create much more advanced shortcodes than this, but this is a good start.

Shortcodes in Widgets & Template Files

Now that you have seen the power of shortcodes, you may be wondering why you can’t use them in your widgets and your template files. Well, it turns out you can.

To activate shortcodes in your widgets, just put the following code in functions.php:

add_filter('widget_text', 'do_shortcode')

And to use a shortcode in your template files, you can access them by using the following:

do_shortcode("[button]");

Ready-to-Use Shortodes

Here are some cool shortcodes you can implement right away.

Code in Posts

If you run a blog that focuses on programming, you probably want to display code in your posts.

function code_shortcode( $attr, $content = null ) {
        $content = clean_pre($content); // Clean pre-tags
        return '<pre"><code>' .
               str_replace('<', '<', $content) . // Escape < chars
               '</code></pre>';
}
add_shortcode('code', 'code_shortcode');

Usage:

[code]&lt;?php echo 'Hello World!'; ?>

Embed Adsense Anywhere on Your Posts

With this shortcode, you can add a Google ad anywhere on your posts simply by using [adsense].

function showads() {
    return '<script type="text/javascript"><!--
    google_ad_client = "pub-XXXXXXXXXXXXXXXX";
    google_ad_slot = "XXXXXXXXXX";
    google_ad_width = XXX;
    google_ad_height = XX;
    //-->
    </script>
    <script type="text/javascript"
    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
    </script>
';
}
add_shortcode('adsense', 'showads');

Embed YouTube Videos

This shortcode will let you embed YouTube videos into your blog posts.

function youtube($atts) {
   extract(shortcode_atts(array(
      "value" => 'http://',
      "width" => '475',
      "height" => '350',
      "name"=> 'movie',
      "allowFullScreen" => 'true',
      "allowScriptAccess"=>'always',
      "controls"=> '1',
   ), $atts));
   return '<object style="height: '.$height.'px; width: '.$width.'px"><param name="'.$name.'" value="'.$value.'"><param name="allowFullScreen" value="'.$allowFullScreen.'"><param name="allowScriptAccess" value="'.$allowScriptAccess.'"><embed src="'.$value.'" type="application/x-shockwave-flash" allowfullscreen="'.$allowFullScreen.'" allowScriptAccess="'.$allowScriptAccess.'" width="'.$width.'" height="'.$height.'"></object>';
}
add_shortcode("youtube", "youtube");

Usage:

// Optional attributes: width, height, name, allowFullScreen, allowScriptAccess, controls  
[youtube value="http://www.youtube.com/watch?v=1aBSPn2P9bg"]

Paypal Donation Shortcode

This shortcode helps you create donation links to your Paypal account.

function donate_shortcode( $atts, $content = null) {
    global $post;extract(shortcode_atts(array(
        'account' => 'your-paypal-email-address',
        'for' => $post->post_title,
        'onHover' => '',
    ), $atts));
    
    if(empty($content)) {
        $content='Make A Donation';
    }
    
    return '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation for '.$for.'" title="'.$onHover.'">'.$content.'</a>';
}
add_shortcode('donate', 'donate_shortcode');

Usage:

[donate]
[donate]Donate Now[/donate]
[donate account="[email protected]" onHover="Thanks" for="Title"]
[donate account="[email protected]" onHover="Thanks" for="Title"]Donate Now[/donate]

Private Note to Authors

This last one is clever. With this shortcode, you can create notes in your posts that only the authors can see.

function sc_note( $atts, $content = null ) {
    if ( current_user_can( 'publish_posts' ) )
      return '<div class="note">'.$content.'</div>';
   return '';
}
add_shortcode( 'note', 'sc_note' );

After reading this article, I hope you love WordPress shortcodes as much as I do, and I hope you’ll start implementing them in your own blog.


Top
This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can read our Disclosure Policy at any time.