One neat feature of WordPress plugins is shortcode. Shortcode enables a user to put something like “[myplugin]” in their posts or pages and have it display content from their plugin. Making WordPress shortcode work for you isn’t terribly difficult, but without some help it can be confusing. In this tutorial, I’ll show you how to use shortcode in your plugins.

Shortcode Example

Let’s say you want to print out the current time anywhere in your post where you put “[time]”. Easy enough! Open up your theme’s functions.php and enter the following.

function time_func ( $atts ) { $thetime = time ( ) ; return date ( "g:i A" , $thetime ) ; } add_shortcode ( 'time' , 'time_func' ) ; function time_func($atts) { $thetime = time(); return date("g:i A",$thetime); } add_shortcode('time', 'time_func');

So now, “[time]” will be replaced with the current server time formatted like hour:minute AM/PM. But what if you aren’t sure what format you want the time to come out in? Well, you just need to add an attribute. I’m going to be using PHP’s date() function formatting in this example.

function time_func ( $atts ) { extract ( shortcode_atts ( array ( 'timeFormat' =& gt ; 'g:i A' ) , $atts ) ) ; $thetime = time ( ) ; return date ( $timeFormat , $thetime ) ; } add_shortcode ( 'time' , 'time_func' ) ; function time_func($atts) { extract(shortcode_atts(array( 'timeFormat' => 'g:i A' ), $atts)); $thetime = time(); return date($timeFormat, $thetime); } add_shortcode('time', 'time_func');

What the above code does is add the possibility of an attribute to your shortcode. So you could use it like “[time timeFormat=’d.m.Y’]”, which return today’s date. In the extract function, you can specify the default value (which I set as hour:minute AM/PM). You can add as many attributes as you need to your shortcode.

For more information, please see the WordPress Shortcode API.