Getting Started with WordPress Shortcodes (+Examples)

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 blogpost 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 simply add something like:

[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’re going to create a simple link to our Twitter account, and then add it in 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, just 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 the add_shortcode() function, we can link any php function to our shortcode. In this simple example, all we do is returning a link to our 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 let’s 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 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, is it? 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 embedd the text you want to use like this:

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

To make this button even better, we could add parameters just like we did in the previous example. Let’s add two parameters this time, one for Twitter username and one for 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 can we 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 and template files

Now when you have seen the power of shortcodes, you’re probably wondering why you can’t use them in your widgets and in 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:

do_shortcode("[button]");

Ready-to-use shortodes

Here’s some cool shortcodes you can implement right away.

Code in posts

If you run a blog that focuses on programming you probably want to be able 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!'; ?>

Source: wp-snippets.com →

Embed Adsense anywhere on your posts

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

function showads() {
    return '<script type="text/javascript"><!--
    google_ad_client = "pub-3637220125174754";
    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>
';
}
add_shortcode('adsense', 'showads');

Source: wprecipes.com →

Embed YouTube video

This shortcode will let you embed YouTube videos to 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"]

Source: wpsnipp.com →

Paypal Donation Shortcode

This is a shortcode helps you to 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="you@yoursite.com" onHover="Thanks" for="Title"]
[donate account="you@yoursite.com" onHover="Thanks" for="Title"]Donate Now[/donate]

Source: wp-snippet.com →

Private note to authors

This last one is a clever one. With this shortcode you can create notes in your posts which 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' );

Source: wprecipes.com →

Conclusion

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.

Author: (1 Posts)

Filip Stefansson is a Swedish developer. Founder of WP-Snippets and co-founder of Pixby. You can connect with Filip @filipstefansson.

Comments