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 ) {
	    '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;
add_shortcode('related_posts', 'related_posts_shortcode');




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


[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 type="text/javascript"

add_shortcode('adsense', 'showads');



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


[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.

function readRss($atts) {
	"feed" => 'http://',
      "num" => '1',
    ), $atts));

    return wp_rss($feed, $num);

add_shortcode('rss', 'readRss');


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


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

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



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


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


[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.