
10 incredibly cool WordPress shortcodes
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/
By the way, did you already visited our new sponsor DaThemes? They provide awesome WordPress themes as well as a great affiliate program that you can join and make money.




92 Comments + Trackbacks
6.25.2009
Awesome and very useful tips! Thanks!. I had actually been meaning to write a url shortener for twitter, but have been putting it off for the past few weeks. I am going to give this one a try now! Thanks Again!!!
6.25.2009
Awesome tips, thanks. Especially thanks for adsense trick.
6.25.2009
Good stuff, I’m going to use some of these on the re-design of my site. Thanks!
6.25.2009
Really great useful shortcodes.
6.25.2009
WOW, this is great! I love Display your blog stats using shortcodes! Good tip.
6.25.2009
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
6.25.2009
Nice shortcuts! Thank you for sharing.
6.25.2009
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.
6.25.2009
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.
6.25.2009
@Justin Tadlock: I’m very sorry for the (now corrected) mistake.
6.26.2009
Great tutorial! Thank you very much!
6.26.2009
This might be useful, thank you
6.26.2009
Very useful! Thanks.
6.26.2009
Great list! I might have to use a few of these now
6.26.2009
Thanks, nice collection of useful tips.
6.26.2009
Great post! Very helpful and useful! Thank you:)
6.27.2009
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.
6.27.2009
@Guresh: Click here to know how to do that
6.27.2009
Awesome. Thanks for the great list!
6.29.2009
Thanks for sharing this very useful shortcode list for wordpress. Some really neat tricks over there.
6.30.2009
Sweet… I am going to be playing with these for a while. Thanks!
6.30.2009
Removing the annoying Wordpress auto-formatting is definitely something I would enjoy using. Now only if that could be turned into a plugin…
7.1.2009
Jean – great job. I really appreciate you giving me these goodies to put in my box of wordpress tricks…
7.3.2009
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?
7.3.2009
Awesome tricks, Thanks.
7.3.2009
Wow… this is what i am looking for. What a awesome tricks. Thanks for sharing mate.
7.4.2009
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/
7.4.2009
Very useful stuff!
7.5.2009
Very nice, thank you for your time!
7.7.2009
Great tips. I will use the adsense one and related posts .
7.8.2009
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
7.12.2009
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
7.16.2009
So far I use adsense and related post. Nice info,thanks
7.17.2009
thank you great content slider..i used it.
7.21.2009
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
7.24.2009
Excellent information, have been meaning to blog about this myself for some time, but you beat me to it.
7.29.2009
Nice article – i might use these in my next blog.
7.31.2009
Short codes is beautiful. For Adsense short code, it gives me inspiration to be applied in my blog.
8.3.2009
Thanks for the post. I like the Adsense one.
8.3.2009
Man you are a genuis. The Adsense one is a real winner. Excellent post!
8.4.2009
Excellent post! useful shortcodes tutorial
8.22.2009
Very good! Thanks for the great list!
9.3.2009
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!!
9.9.2009
this, very thank you..
Your site full professional and very beautiful…
9.9.2009
good stuff! Thank you, I will use some of these on my page!
9.11.2009
Thanks for the very useful list.
9.24.2009
Easy way to add adsense to my post, Thanks man.
11.3.2009
Very, very useful. I’ll be using at least 3 of these on my site.
Thank you for publishing
12.4.2009
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
12.8.2009
Thanks for the post =)) Good work!
12.27.2009
Great post, thank you very much
1.1.2010
Awesome tips, thanks. very useful. I’ll be using at least 2 of these on my site
1.1.2010
I’m addicted to shortcodes. I used to use PHP code everywhere. Now, simple shortcodes suffice.