10 incredibly cool WordPress shortcodes

by Jean. 116 Comments -

Introduced in WordPress 2.5, shortcodes are a very easy way to display lot of things on your blog posts by inserting a very simple code. In this article, I’m going to show 10 incredible things shortcodes can do.

How shortcodes works

There’s already tons of quality articles about WordPress shortcodes. If you’re new to WordPress shortcode, you should consider reading theses posts:

Regarding this article, the codes have to be pasted on your theme functions.php file. Then simply use the shortcode as displayed (Usage…)

1 – Displaying related posts

Related posts are definitely a great way to get your visitors staying longer on your blog. Sure, there’s tons of plugins to display them, but what about a simple shortcode?

function related_posts_shortcode( $atts ) {
	extract(shortcode_atts(array(
	    'limit' => '5',
	), $atts));

	global $wpdb, $post, $table_prefix;

	if ($post->ID) {
		$retval = '<ul>';
 		// Get tags
		$tags = wp_get_post_tags($post->ID);
		$tagsarray = array();
		foreach ($tags as $tag) {
			$tagsarray[] = $tag->term_id;
		}
		$tagslist = implode(',', $tagsarray);

		// Do the query
		$q = "SELECT p.*, count(tr.object_id) as count
			FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id  = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
				AND p.post_status = 'publish'
				AND p.post_date_gmt < NOW()
 			GROUP BY tr.object_id
			ORDER BY count DESC, p.post_date_gmt DESC
			LIMIT $limit;";

		$related = $wpdb->get_results($q);
 		if ( $related ) {
			foreach($related as $r) {
				$retval .= '<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>';
			}
		} else {
			$retval .= '
	<li>No related posts found</li>';
		}
		$retval .= '</ul>';
		return $retval;
	}
	return;
}
add_shortcode('related_posts', 'related_posts_shortcode');

Usage:

[related_posts]


Source:
http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress

2 – Show a Google chart

The Google Charts API is probably the easiest way to create dynamic charts online. here is a shortcode to make the process even easier on your WordPress blog.

function chart_shortcode( $atts ) {
	extract(shortcode_atts(array(
	    'data' => '',
	    'colors' => '',
	    'size' => '400x200',
	    'bg' => 'ffffff',
	    'title' => '',
	    'labels' => '',
	    'advanced' => '',
	    'type' => 'pie'
	), $atts));
 
	switch ($type) {
		case 'line' :
			$charttype = 'lc'; break;
		case 'xyline' :
			$charttype = 'lxy'; break;
		case 'sparkline' :
			$charttype = 'ls'; break;
		case 'meter' :
			$charttype = 'gom'; break;
		case 'scatter' :
			$charttype = 's'; break;
		case 'venn' :
			$charttype = 'v'; break;
		case 'pie' :
			$charttype = 'p3'; break;
		case 'pie2d' :
			$charttype = 'p'; break;
		default :
			$charttype = $type;
		break;
	}
 
	if ($title) $string .= '&chtt='.$title.'';
	if ($labels) $string .= '&chl='.$labels.'';
	if ($colors) $string .= '&chco='.$colors.'';
	$string .= '&chs='.$size.'';
	$string .= '&chd=t:'.$data.'';
	$string .= '&chf='.$bg.'';
 
	return '<img title="'.$title.'" src="http://chart.apis.google.com/chart?cht='.$charttype.''.$string.$advanced.'" alt="'.$title.'" />';
}
add_shortcode('chart', 'chart_shortcode');

Usage:

[chart data="41.52,37.79,20.67,0.03" bg="F7F9FA" labels="Reffering+sites|Search+Engines|Direct+traffic|Other" colors="058DC7,50B432,ED561B,EDEF00" size="488x200" title="Traffic Sources" type="pie"]

Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress

3 – Integrate Adsense ads

Adsense is probably the easiest way to make money online and most bloggers are using it in order to earn an online income. using widgets , you can easily add Adsense ads in your blog sidebar, but the best way to get clicks from visitors is definitely to integrate Adsense in your posts. The whole process is incredibly easy, using WordPress shortcodes.

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');

Usage:

[adsense]

Source: http://www.wprecipes.com/how-to-embed-adsense-anywhere-on-your-posts

4 – Display member-info content using a WordPress shortcode

Since some months, more and more blogs are creating “members-only” section, featuring premium downloads and infos. Do you know how easy is it to display some “member-only” content on your blog, using a shortcode?

function access_check_shortcode( $attr, $content = null ) {
    extract( shortcode_atts( array( 'capability' => 'read' ), $attr ) );
    if ( current_user_can( $capability ) && !is_null( $content ) && !is_feed() )
        return $content;

    return 'Sorry, only registered members can see this text.';
}

add_shortcode( 'access', 'access_check_shortcode' );

Usage:

[access capability="switch_themes"]

Source: http://justintadlock.com/archives/2009/05/09/using-shortcodes-to-show-members-only-content

5 – Embeddable RSS feed reader

Among other great things, WordPress have a built-in RSS reader, used to display feeds on your dashboard. I already shown how you can use it on your blog sidebar (or header, footer, etc…), but with a shortcode, you can even insert it on your posts.

//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');

Usage:

[rss feed="http://feeds2.feedburner.com/Catswhocode" num="5"]  

Source: http://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/

6 – Automatically create a short url for Twitter

If you’re on Twitter, you know how short urls are usefull. But a definitely boring thing when you want to tweet a blog post is to create the short url yourself. So, what about using a shortcode to make your readers life easier?

function subzane_shorturl($atts) {
	extract(shortcode_atts(array(
		'url' => '',
		'name' => '',
), $atts));
$request = 'http://u.nu/unu-api-simple?url=' . urlencode($url);
$short_url = file_get_contents($request);
	if (substr($short_url, 0, 4) == 'http')    {
		$name = empty($name)?$short_url:$name;
		return '<a href="'.$short_url.'">'.$name.'</a>';
	} else {
		$name = empty($name)?$url:$name;
		return '<a href="'.$url.'">'.$name.'</a>';
	}
}
add_shortcode('shorturl', 'subzane_shorturl');

Usage:

[shorturl name="shortcode" url="http://codex.wordpress.org/Shortcode_API"]

Source: http://www.subzane.com/2009/05/shortcode-advantage-unus-url-shortener/

7 – Display the last image attached to post

Instead of dealing with image url, a simple shortcode can retrieve and display the last image attached to post:

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");

Usage:

[postimage]

Source: http://www.wprecipes.com/wordpress-shortcode-easily-display-the-last-image-attached-to-post

8 – Add administration notes on posts

If you’re owning a multi-author blog, it should be useful to be able to leave messages on posts that can only be seen by other admins. For example, the blog owner should add a message on a post, asking the writer to correct a mistake or add more info.

add_shortcode( 'note', 'sc_note' );

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

Usage:

[note]This is a personal note that only admins can see![/note]

Source: http://www.wprecipes.com/add-private-notes-to-your-wordpress-blog-posts

9 – Remove WordPress automatic formatting

If you’re used to display code snippets on your blog, you know that WordPress automatic formatting can be a pain for developers. The solution is simple: Using a shortcode to remove the auto-formatting functions on certain portions of text.

function my_formatter($content) {
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
			$new_content .= $matches[1];
		} else {
			$new_content .= wptexturize(wpautop($piece));
		}
	}

	return $new_content;
}
	
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');

add_filter('the_content', 'my_formatter', 99);

Usage:

[raw]This portion of text will not be automatically formatted by WP.[/raw]

Source: http://wordpress.org/support/topic/280732

10 – Display your blog stats using shortcodes

Ever wished to be able to display your blog stats, in real time? Thanks to Wesley and his “Blog Stats” plugin, you can display stats info as such as number of posts, number of comments, average comments per post, google pagerank, alexa rank, etc, using simple shortcodes.
The Blog Stats plugin can be downloaded here and have to be installed on your blog just as you install any other plugin.
Usage:

[pagerank]
[feedburner_subscribers]
[alexa_rank]
[technorati_authority]
[technorati_rank]
[user_count]
[post_count]
[page_count]
[comment_count]
[trackback_count]
[avg_comments_per_post]
[category_count]
[tag_count]
[link_count]
[google_backlinks]
[yahoo_backlinks]
[delicious_bookmarks]

Source: http://www.improvingtheweb.com/wordpress-plugins/blog-stats/

  • Pingback: links for 2009-06-25 | Links | WereWP

  • Pingback: 10 incredibly cool WordPress shortcodes « Netcrema - creme de la social news via digg + delicious + stumpleupon + reddit

  • http://shakin.ru/ Mike

    Awesome tips, thanks. Especially thanks for adsense trick.

  • Pingback: Wordpress News - 10 incredibly cool WordPress shortcodes

  • http://www.vagrantradio.com Jason

    Good stuff, I’m going to use some of these on the re-design of my site. Thanks!

  • http://wpcult.com The Frosty @ WPCult

    Really great useful shortcodes.

  • Pingback: 10 incredibly cool WordPress shortcodes

  • http://freetypography.com/ Philipp

    WOW, this is great! I love Display your blog stats using shortcodes! Good tip.

  • http://safe.mn/ Julien

    For 6., create a short link, there is much more simple: insert just one line. I cannot copy the link in the comment, check http://safe.mn/tools#automatic

  • Pingback: 10 incredibly cool WordPress shortcodes | eWebsite.biz

  • http://jamesmcwhorter.com James McWhorter

    Nice shortcuts! Thank you for sharing.

  • http://justintadlock.com Justin Tadlock

    I’m addicted to shortcodes. I used to use PHP code everywhere. Now, simple shortcodes suffice.

    By the way, your source for the members-only shortcode is a direct copy of my tutorial on showing members-only content with shortcodes.

  • http://www.mediacontour.com Media Contour

    With the thousands of WordPress plug-ins that are out there, it is refreshing to find a resource for some useful shortcodes. These shortcodes save a lot of time, especially when you’re frequently updating, modifying, and adding to your blog. These shortcodes can also do wonders to clean up messy coding.

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Justin Tadlock: I’m very sorry for the (now corrected) mistake.

  • Pingback: En vrTrucs et astuces pour wordpress | KubX

  • http://aslamnajeem@gmail.com Mohamed Aslam

    Great tutorial! Thank you very much!

  • Pingback: Daily Digest for June 25th | Digital Gilbert

  • http://designawardsgallery.com/ Best CSS Gallery

    This might be useful, thank you

  • Pingback: ♥ Top 10 Codici da utilizzare per Wordpress | Tecnofollia

  • http://www.wordpressgala.net/ WORDPRESSGALA

    Very useful! Thanks.

  • Pingback: 10 incredibly cool WordPress shortcodes

  • Pingback: 10 wordpress shortcodes | Yloz féle zacc

  • Pingback: Linky-Link, here are the new links to retweet =) « Adrian Zyzik’s Weblog

  • http://beyondrandom.com BeyondRandom

    Great list! I might have to use a few of these now :)

  • http://blog.sevenapril.com/ midbach

    Thanks, nice collection of useful tips.

  • Pingback: Couteau Suisse N°38 la série des trouvailles

  • Pingback: Technology Links: 2009-06-26

  • http://www.brilliantlifedesign.com Melissa Foster

    Great post! Very helpful and useful! Thank you:)

  • Pingback: links for 2009-06-26 | Digital Rehab

  • Pingback: - leg med nye medier. Eller noget.

  • Pingback: links for 2009-06-26 — Chroniques du web

  • Guresh

    I tried to use related posts short code. Instead of adding the usage of [related_posts] in every post, can i add directly in template page.

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Guresh: Click here to know how to do that :)

  • Pingback: Couple good finds for the day « Cool Web Finds

  • http://www.spiritualmind.com Alex

    Awesome. Thanks for the great list!

  • Pingback: Using WordPress’ Excerpt (the_excerpt) creatively | Nometech.com

  • Pingback: Prototype Log » Blog Archive » 10 incredibly cool WordPress shortcodes

  • Pingback: 10 shortcodes para hacerte la vida más fácil con Wordpress | aNieto2K

  • Pingback: Eiencafe.com --> New way to graphic

  • Pingback: myWordPress.de

  • Pingback: Dario Salvelli’s Blog » Blog Archive » Feedmastering #156 (versione postuma di Venerdì scorso)

  • http://www.0window.com/blog/ Catrin W

    Thanks for sharing this very useful shortcode list for wordpress. Some really neat tricks over there.

  • http://www.joshstauffer.com Josh

    Sweet… I am going to be playing with these for a while. Thanks!

  • http://www.insidethewebb.com/ Jake Rocheleau

    Removing the annoying WordPress auto-formatting is definitely something I would enjoy using. Now only if that could be turned into a plugin…

  • http://www.howtocontrolmrsa.com Christine

    Jean – great job. I really appreciate you giving me these goodies to put in my box of wordpress tricks…

  • Pingback: Knowledge Base

  • Pingback: 10 incredibly cool WordPress shortcodes « wp-popular.com

  • Pingback: Sket pÃ¥ nettet den 02.07.09

  • http://www.serradinho.com George Serradinho

    Thanks for the tips. I have a plugin installed for related posts, but I’m trying to bring down the plugins that are installed on my site. I will try your code and see if it works.

    Do you know if this would work with Thesis theme?

  • http://bestgptr.blogspot.com Edos

    Awesome tricks, Thanks.

  • http://www.greencomestrue.com Todo

    Wow… this is what i am looking for. What a awesome tricks. Thanks for sharing mate.

  • Pingback: Arbenting’s Weekly Inspiration and Best of the Web #11 | Arbenting

  • Pingback: lillbra » Blog Archive » links for 2009-07-03

  • http://hjacob.com/blog/ Hendrik Jacob

    The Short URL Shortcode has a flaw -> it will generate the shortened URL over and over again (with every page request). i released a plugin (with shortcode support) which caches the url and gives a better performance.

    it can be found at http://wordpress.org/extend/plugins/shortcode-shorturl/

  • http://www.theapplebottomjeans.com Haigo Hein

    Very useful stuff!

  • http://www.games321.net Nick V.

    Very nice, thank you for your time!

  • Pingback: Top 10 WordPress hacks from June ‘09

  • http://www.niharsworld.com/ Nihar

    Great tips. I will use the adsense one and related posts .

  • http://pomegranateinformation.com/pomegranate/pomegranate-tree/ tonya jones

    hey Jean i must appreciate your work dude..your posts are really making use of wordpress easy for the newbie like me….i was looking forward for shortcodes thanks

  • http://www.ambertilesmaroochydore.com George

    Your tips are really useful for self web site designers and I’m one of them. I’m sure these tricks will help me a lot to develop my skills.

    Thanks

    George

  • http://supportmentorschools.com kurnia

    So far I use adsense and related post. Nice info,thanks

  • http://www.aavsa.com avÅŸa

    thank you great content slider..i used it.

  • Pingback: New And Comprehensive Wordpress 2.8 Tutorial and Hack Toolbox | Graphic and Web Design Blog - Inspiration, Resources and Tools

  • http://www.mbreti3gut.com roko

    Thanks you for these codes, especially for the 5th – Embeddable RSS feed reader. But, I need more of this; if possible to use some excerpts. Thank you

  • http://www.deregular.com Chloe

    Excellent information, have been meaning to blog about this myself for some time, but you beat me to it.

  • http://www.corporategraphicdesign.co.uk Mr Jones

    Nice article – i might use these in my next blog.

  • http://babytipz.com Keiy

    Short codes is beautiful. For Adsense short code, it gives me inspiration to be applied in my blog.

  • Pingback: 10 unglaubliche WordPress ShortCodes » Google, Code, AdSense, Artikel, Aber, Codes » fgBlog.de

  • http://www.am-3.org Dave B

    Thanks for the post. I like the Adsense one.

  • http://www.make-easy-money-directory.com Chris

    Man you are a genuis. The Adsense one is a real winner. Excellent post!

  • Pingback: New And Comprehensive Wordpress 2.8 Tutorial and Hack Toolbox - Programming Blog

  • http://donyariyus.com ariyus

    Excellent post! useful shortcodes tutorial

  • Pingback: וורדפרס - שימוש בקיצורים - הבלוג של אח"×™ דקר

  • Pingback: Using WordPress’ Excerpt (the_excerpt) Creatively | WPShout.com

  • http://www.netz-online.com Susi

    Very good! Thanks for the great list!

  • Pingback: Shortcodes for WordPress… | Christine â„¢ aka Big Pink Cookie - Helping Photographers Have Better Blogs & Businesses

  • John

    For tip #4, is there any way I can get this to work with post excerpts?

    Right now, if a post is within the [member] tags, nothing shows up in the excerpts. I’d like it to say something like “This post is viewable to members only”. Love the tip on the shortcodes!!

  • http://www.turksbilisim.com Türks BiliÅŸim

    this, very thank you..

    Your site full professional and very beautiful…

  • http://www.rentinaix.com Aix

    good stuff! Thank you, I will use some of these on my page!

  • http://vorona7001.org.ua Impec

    Thanks for the very useful list.

  • http://swingoutthailand.com/ Tom

    Easy way to add adsense to my post, Thanks man.

  • Pingback: Wordpress Tricks And Hacks » Softloads

  • http://blogpig.com BlogPiG

    Very, very useful. I’ll be using at least 3 of these on my site.

    Thank you for publishing

  • Pingback: Puntos de vista » Blog Archive » Mostrar un feed rss en wordpress

  • Pingback: jawe.net » Blog Archiv » Links vom Thursday, 19. November 2009

  • http://www.geoweb.blog.br George Campos

    Great Wok!

    with your tips, I developer my first shortcodes

    // return link for own post by George Campos
    // you can use with the tag for example
    function change_link() {
    global $wpdb, $post, $table_prefix;
    $permalink = get_permalink($post->ID);
    return $permalink;

    }
    add_shortcode(‘post_link’, ‘change_link’);

    Call [post_link] in the post

    Thanks

  • Pingback: WordPress ShortCodes | mgBlog

  • http://www.gidin.com.ua/ Gidin

    Thanks for the post =)) Good work!

  • http://Ghosts-IT.com Radz Nguyen

    Great post, thank you very much :)

  • http://softfive.com chevin

    Awesome tips, thanks. very useful. I’ll be using at least 2 of these on my site

  • http://ghosts-it.com radz nguyen

    I’m addicted to shortcodes. I used to use PHP code everywhere. Now, simple shortcodes suffice.

  • http://wpsecurity.org/ Alex

    Great! Very useful shortcodes.Thanks for sharing.

  • Pingback: Arbenting’s Weekly Inspiration and Best of the Web #11 » Arbenting - The Act of Being Creative

  • http://www.sports-news.com.ua/ Artem

    Excellent post! ;)

  • http://www.sluff.de Sluff

    Oh great… number 9 saved my live!

  • Pingback: uberVU - social comments

  • http://www.onlinemarketizing.com John Miles

    Fantastic post, been looking at a lot of WordPress templates lately and there are a lot of shortcodes mentioned, it’s nice to know how to implement them in my own templates as they are especially useful for layout columns and styling up your blog.

  • http://obzorurokov.ru/ Mary

    Thanks for the nice article!

  • http://www.oyunyolu.net Oyunlar

    Thanks for the nice article!

  • http://everydayeve.com Eve @ Everyday Eve

    Where can I find more info on the syntax for using google charts? Having trouble inserting a line chart… trying to google it but it is either hard to find or I just need to go to bed LOL

    great post by the way!

  • http://www.onlinemarketizing.com John Miles

    What a great resource for shortcodes for WordPress. The more I look a shortcodes the better it is for my clients, who are not really savvy when it comes to layout and css. This is a great reference, thanks.

  • http://saatbaba.com saat

    Where can I find more info on the syntax for using google charts? Having trouble inserting a line chart… trying to google it but it is either hard to find or I just need to go to bed LOL

  • http://postarticlesplus.net/ Alex Pablate

    Nice stuff about WordPress shortcut!

    I was unaware of these things but today, I learned a lot from this post!

    Very nice work, keep it up please!

  • http://www.detailcommunications.com David Schmeikal

    Some great stuff here!
    I’m looking to for a shortcode that would allow you to pick a post id and drop that post content, thumbnail and excerpt and place it anywhere.
    Any ideas where I would find that?

  • http://crunchpixels.com.au Jason

    Great Article. Although i already use variations of most of these shortcodes, i will be adding the Google Charts & Remove WordPress Auto Formatting to the ever increasing arsenal of helpful inclusions.

  • http://www.softwarefactoryinc.com Andrew

    Very cool but I believe WordPress does not like attributes for a full URL. It mangles them unless you are are html editor mode.

  • http://www.redbridgenet.com Red Bridge

    Best post I’ve read so far today. Shortcodes are an underutilized yet extremely powerful tool in WordPress.

  • http://vitorteixeira.co.cc/ victei

    Hello, I have need of Shortcodes and never arrived here. Today she researched other matter found it. ;)
    Very good post, very helpful for those looking to make the most WP.

    A hug …

  • http://www.valuecruises.net Thomas

    Loving the Adsense integration. I always have trouble entering it in the HTML editor. My theme always ends up stripping something out!

  • http://rakateja.wordpress.com Made Raka

    where i put the code function?thank you

    • http://www.danieldeepak.com Daniel Deepak

      You can use functions.php

  • http://thegoodarticle.com victei

    Very useful some of these codes, I’ll use some of them on my blog and leave some plugin side. thanks!

  • http://www.danieldeepak.com Daniel Deepak

    It seems that the last plugin isn’t working. I tried with [pagerank]. Can you help???

  • http://kovshenin.com Konstantin Kovshenin

    Number 8 (admin notes) has a security issue — admin notes will become visible to all readers when the shortcode/plugin is disabled, broken, etc. Not the best way to store sensitive data.. I’d suggest post meta instead.

  • http://www.freeproxieslist.org/ Francesca Borri

    I like this web site very much, Its a really nice spot to read and get information.

  • http://www.cliquejogar.com/ cliquejogar.com

    good