How To Use, Style and Implement WordPress Shortcodes

WordPress shortcode API is a powerful function which was introduced from version 2.5, it’s just a simple set of functions for creating macro codes in post content. If you’ve developed a Vbulletin forum before, you would have been familiar with the shortcode (something called BBCode) but the WordPress users maybe not. In this article, I would like to show you how to create and use shortcodes, in addition, I will show you some creative examples of using shortcode in WordPress blog.

What Are Shortcodes?

The shortcodes I’m going to introduce are very simple and easy to use, they look like this:

, [clip][/clip], [flv][/flv], [flash][/flash].....

The shortcodes may have attributes or without attributes, so we will go from the easy first.

WordPress Shortcodes without attributes

Example of the shortcodes without attributes:


How to create? It’s most simple, let’s add the code below to your functions.php file (stored in your current theme directory):

function text() {
return 'Good morning'; } add_shortcode('gm', 'text');

As you see in the code above, the first thing I do is create a function like any other WordPress functions, the function will return the text “Good morning” when called then I add the API call to register the shortcode handler:

add_shortcode('gm', 'text');

The first parameter is a name of the shortcode and the second parameter is the name of the function will be called, in my situation is “text”.

How to use? When posting a new article, whenever you want to display the “Good morning” text, switch the editor to HTML mode and type the following shortcode:

[gm]

WordPress Shortcodes with attributes

WordPress Shortcodes with attributes are more complicated, for example:


The code you should add to your functions.php is:

function text($atts) {
	extract(shortcode_atts(array(
		'attribute' => 'Good morning' // The default value if you do not pass the attribute to the shortcode
	), $atts));

	return $attribute;
}
add_shortcode('gm', 'text');

How to use? With attributed shortcode you should pass the value of the attributes to the shortcode when using, if not, the function will use the default value:

[gm attribute="Good night"]

… will output “Good night”, but:

[gm]

… will output “Good morning”

WordPress Shortcodes with attributes and content

After reading and trying two trivial examples above, it’s the time to go to the WP shortcodes which you will deal with a lot of time, let’s see this example:

function a($atts, $content = null) {
	extract(shortcode_atts(array(
        "class" => '',
        "rel" => '',
		"url" => ''
	), $atts));
	return '<a class="'.$class.'" rel="'.$rel.'" href="'.$url.'">'.$content.'</a>';
}
add_shortcode('link', 'a');

Notes:

  • $atts: an array of attributes.
  • $content: the enclosed content.

So if the shortcode I place on the post editor is:

[link url="http://www.google.com" rel="nofollow" class="hyperlink"]Google[/link]

… the result will be:

<a class="hyperlink" rel="nofollow" href="http://www.google.com">Google</a>

Other ways of using this shortcode:

[link] or [link/] will return: <a></a>
[link]Google[/link] will return <a>Google</a>

Shortcodes were parsed after post formatting was applied so If you do want your shortcode output to be formatted, you should call wpautop() or wptexturize() directly when you return the output from your shortcode handler.WordPress.org

WordPress shortcode is not too hard to understand, and it help you to create a dynamic content for your web blog, you could make anything you want with it, the only limitation is just your imagine, next up I would like to show you how to take advantage of it.

Create Special List Styles

checklist

You could create a special list styles easily with shortcodes, first add the code below to your functions.php file:

function checklist($atts, $content = null) {
	return '
<div class="checklist">'.$content.'</div>
';
}
add_shortcode('checklist', 'checklist')

This shortcode will wrap the <div> around the specific content and we will markup this <div> element by adding to your css file:

.checklist ul {
margin-left:50px;
list-style:none!important
}
.checklist ul li{
padding:5px 5px 5px 30px;
background:#fff url(images/check.png) no-repeat center left
}

Using:

[checklist]
<ul>
	<li>Lorem ipsum dolor sit amet</li>
	<li>Lorem ipsum dolor sit amet</li>
	<li>Lorem ipsum dolor sit amet</li>
	<li>Lorem ipsum dolor sit amet</li>
</ul>
[/checklist]

Thanks to http://www.dezinerfolio.com for the free icon set.

Create Box Styles

box-style

The code:

function box($atts, $content = null) {
	return '
<div class="box">;'.$content.'</div>
';
}
add_shortcode('box', 'box');
The css:

Using:

<h3>Create Dropcaps</h3>
<img src="http://35.226.78.216/wp-content/uploads/2010/06/dropcap1.png" alt="dropcap" width="517" height="96" />

The code:
function dropcap($atts, $content = null) {
	return '
<div class="dropcap">'.$content.'</div>
;';
}
add_shortcode('dropcap', 'dropcap');
]

The css:

.dropcap {
display:block;
float:left;
font-size:50px;
line-height:40px;
margin:0 8px 0 0;
}

Using:

Mauris ut lectus erat. In ...

Create A Download Button

download

The code:

function download($atts, $content = null) {
	extract(shortcode_atts(array(
		"url" =&gt; ''
	), $atts));
	return '<a class="download" href="'.$url.'">'.$content.'</a>';
}
add_shortcode('download', 'download');

The css:

.download {
display: inline-block;color:#fff;
font-weight:bold;
font-size:1.2em;
background : -webkit-gradient(linear, left top, left bottom, from(#88c841), to(#73b338));
background : -moz-linear-gradient(center top, #88c841, #73b338);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
padding: 5px 20px;
text-align: center;
-shadow: 0px 1px 0px #6c0909;
}

.download:hover {
background : -webkit-gradient(linear, left top, left bottom, from(#73b338), to(#88c841));
background : -moz-linear-gradient(center top, #73b338, #88c841);
}

Using:

[download url="http://www.google.com"]Download Google Chrome[/download]

Jquery Slide Up / Slide Down Shortcode

scroll

The code:

function slide($atts, $content = null) {
	extract(shortcode_atts(array(
		"title" =&gt;; ''
	), $atts));
	return '<a class="slide">'.$title.'</a>

'.$content.'

';
}
add_shortcode('slide', 'slide');

The css:

.slide {cursor:pointer}
.slide-next {display:none}

The Javascript: (You can add the javascript code to your footer.php file)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"><!--mce:0--></script>
<script type="text/javascript"><!--mce:1--></script>

Using:

Mauris ut lectus erat. In condimentum, turpis ac ...

Post Content In Column

column

The code:

function half($atts, $content = null) {
	return '
<div class="half">'.$content.'</div>
';
}
function half_last($atts, $content = null) {
	return '
<div class="half-last">'.$content.'</div>
<br style="clear: both;" />';
}
add_shortcode('half', 'half');
add_shortcode('half_last', 'half_last');

The css:

.half, .half-last {float:left;width:47%;margin:10px 0;margin-right:6%;}
.half-last {margin-right:0}

Using:

[half]Mauris ut lectus erat. In condimentum, turpis ...[/half]

[half_last]Mauris ut lectus erat. In condimentum, turpis ...[/half_last]

Of course, you could modify the code to create 3,4 or 5 columns post layout as your needs :).

Create A Multiple URL Shortener Shortcode

This is an exclusive WordPress Shortcode I created for Tuttoaster.com, all you need to do is give shortcode the URL then it will shorten via the most 4 popular sevices: : tinyURL, Google shortener, is.gd and Su.pr (Stumbleupon), paste the code below to your functions.php file:

function getContent($url) {
    $content = '';
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $content = curl_exec($ch);
        curl_close($ch);
    }
    elseif (ini_get('allow_url_fopen')) {
        $content = file_get_contents($url);
    }
    return $content;
}

function short($atts) {
	extract(shortcode_atts(array(
		"url" =&gt; ''
	), $atts));
	$googledata = getContent("http://ggl-shortener.appspot.com/?url=$url");
    $googlejson = json_decode($googledata);

	$isgd = getContent("http://is.gd/api.php?longurl=$url");
	$tinyurl = getContent("http://tinyurl.com/api-create.php?url=$url");
	$google = $googlejson-&gt;short_url;
	$supr = getContent("http://su.pr/api?url=$url");

	$output = '
<ul>';
	$output .= '
	<li>Is.gs: <a href="'.$isgd.'">'.$isgd.'</a></li>
';
	$output .= '
	<li>Google: <a href="'.$google.'">'.$google.'</a></li>
';
	$output .= '
	<li>Tinyurl:<a href="'.$tinyurl.'">'.$tinyurl.'</a>;</li>
';
	$output .= '
	<li>Su.pr: <a href="'.$supr.'">;'.$supr.'</a></li>
';
	$output.='</ul>
';
	return $output;
}
add_shortcode('short', 'short');

How to use? It’s very simple, huh?:

[short url="http://url-need-to-be-shortened.com"]

And the result would be:

url-short

In the shortcode code above, I think you should register for the services account and using the callback with APIKey then your post content does not need to re-shorten the URL every-time loaded.

The next following is 2 shortcodes which I like most and I want to introduce to you:

Get posts from WordPress Database with a Shortcode

The code:

function sc_liste($atts, $content = null) {
        extract(shortcode_atts(array(
                "nombre" =&gt; '5',
                "cat" =&gt; ''
        ), $atts));
        //requete sur la BDD pour recuperr la liste de billet
        global $post;
        $myposts = get_posts('numberposts='.$nombre.'&amp;order=DESC&amp;orderby=post_date&amp;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>
';
        //on renvoi la liste
        return $retour;
}
add_shortcode("liste", "sc_liste");

Using: (It will display 3 posts from the category ID = 1)

[liste nombre="3" cat="1"]

The code source.

Hide Content From The Public

The code:

function guest_check_shortcode( $atts, $content = null ) {
	 if ( ( !is_user_logged_in() &amp;&amp; !is_null( $content ) ) || is_feed() )
		return $content;
	return '';
}
add_shortcode( 'guest', 'guest_check_shortcode' );
function member_check_shortcode( $atts, $content = null ) {
	 if ( is_user_logged_in() &amp;&amp; !is_null( $content ) &amp;&amp; !is_feed() )
		return $content;
	return '';
}
add_shortcode( 'member', 'member_check_shortcode' );

Using:

Conclusions

After reading my article, I hoped that you will have more knowledge about WordPress Shortcode and might be it will make your blog life easier, if you have any new or better idea or in need of help with implementing these functions, please do not hesitate to contact us.

If you found typing the shortcode cost you too much time then you could download the Post Editor Buttons plugin, the plugin allows you to add your own buttons to the post editor’s toolbar so let’s make a button with your shortcode tags.

Other WordPress Shortcodes Resources

Take advantage of cheap printing services that are well designed and in full vivid colors.

PassCertification provides most up-to-date Security+ preparation materials including Comptia Network+ preparation sample Questions & Answers. Get our Network+ questions and CompTIA A+ Questions and pass your exam with ease.

Sponsor: Hondennamen
Recommend: http://mywindows8themes.com

<!–Get professional testking 156-315 web designing training to learn how to use style and implement wordpress shortcodes. Become expert in wordpress using testking E20-340 tutorials and testking 1z0-050 guide.–>

This entry was posted on Wednesday, June 23rd, 2010 at 08:13 and is filed under Tutorials, Wordpress. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Jennifer R is a banking student who love to work with Php, Wordpress blog and Css design... She is the chief editor of Intenseblog and Highcoupon website. Want to keep up with her? Follow Jennifer R on Twitter!

About the author Published by Jennifer R

30 Responses »

  1. Is that a great list of things to do or what? I’ve been using shortcodes for a while but the examples here get the use of shortcodes further than the usual thing. A great resource to bookmark. Thanks Jennifer.

  2. That is a really nice technique I did not know about. Thanks!

  3. realy nice
    but i stil using joomla now

  4. Now that’s a list worth bookmarking! Thanx these will come in handy

  5. Excellent Article, keep positng like this.

  6. At first I was like, why the hell would I want to post static content like your “Good Morning” example…and then I saw the Download Button example, and everything started to make sense. I believe I will have to start using these short codes. Good tutorial and examples.

  7. Man, this post is such a lifesaver! I was wasting time trying to make TinyMCE Advanced do what I wanted it to do, which was apply a style, as a to part of a post, in a way that is easy to implement. Your shortcodes with the applied styles worked perfectly. Thank-you for this wonderful resource!

  8. Great compilation. +1

  9. hello,

    Trying to use the shortcodes but can’t seem to get it to work? Can you help?

    I added to the 2010Weaver Functions

    function box($atts, $content = null) {

    return ‘
    ;’.$content.’
    ‘;

    } add_shortcode(‘box’, ‘box’);

    Then added to the 2010Weaver CSS:

    .box {

    background:#bfe4f9;

    border:1px solid #68a2cf;

    -moz-border-radius: 5px;

    -webkit-border-radius: 5px;

    padding:10px

    }

    still nothing?

    I get this on my post:

    ;TEST BOX[\box]

    Any help would be appreciated…thanks!

  10. Absolutely fantastic post.

  11. These are really helpful scripts… saved lots of my time..so wanna say thanks for sharing

  12. Hey Jennifer, I really love these examples. You’ve explained the use very well. There’s only one (I think) mistake in your post, it’s in the “Create Box” tutorial, you’ve included the css/html in the code post.

    Thanks, see ya 🙂

  13. Some great ideas for shortcodes! AND so nicely explained.
    Thanks Jennifer R 🙂

  14. Thank you, this was very helpful

  15. Awesome article 🙂

  16. These Short codes really helps me

  17. Thank you, very nice post and actually some nice uses of shortcode, especially the link shortener. I use it was well to display my adverts in posts.

    I spotted just one mistake, in the part where you can make the shortcode for a download button, on line 3 it says:
    “url” => ‘

    ‘>’ should be ofcourse ‘>’

    But nevertheless, thanks for sharing!

  18. Awesome article,thanks.. it really helped me.