10 incredibly cool WordPress shortcodes

by Jean. 115 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 ) {
	    '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"]

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) {
		"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.
The Blog Stats plugin can be downloaded here and have to be installed on your blog just as you install any other plugin.


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

Comments (115) - Leave yours

  1. Julien said:

    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

  2. Media Contour said:

    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.

  3. Guresh said:

    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.

  4. Eiencafe.com --> New way to graphic said:

    Weekly Fave’s…

    While I’m in Oropa vacationing (well sightseeing ) here my favorites of the week (gotta love the scheduled post of WP).
    Week from June 21 to June 27, 2009:
    10 Common Mistakes In Logo Design
    Photoshop Photo Manipulate a Falling Ange…

  5. myWordPress.de said:

    10 unglaubliche WordPress ShortCodes…

    Auf catswhocode.com wurde vor drei Tagen ein interessanter Artikel veröffentlicht, welcher 10 interessante ShortCodes beschreibt, so dass etwas für Google oder auch Twitter dabei ist.
    Was auch interessant sein dürfte ist der Google AdSense Code, s…

  6. George Serradinho said:

    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. Hendrik Jacob said:

    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/

  8. tonya jones said:

    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

  9. George said:

    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.



  10. roko said:

    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

  11. John said:

    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!!

  12. George Campos said:

    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


  13. John Miles said:

    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.

  14. Eve @ Everyday Eve said:

    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!

  15. John Miles said:

    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.

  16. saat said:

    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

  17. David Schmeikal said:

    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?

  18. Jason said:

    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.

  19. victei said:

    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 …

  20. Thomas said:

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

  21. Konstantin Kovshenin said:

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!