Categories
PHP Programming Wordpress Development

WordPress Shortcode API Tutorial

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.

Wordpress Shortcode API Tutorial

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

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' => '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.

By Jack Slingerland

Founder of Kernl.us. Working and living in Raleigh, NC. I manage a team of software engineers and work in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and son, lifting weights, and advancing Kernl.us in my free time.

3 replies on “WordPress Shortcode API Tutorial”

Hi,

Thanks for this example. There is a fatal error in line 4 of second example – missing comma – should be:
), $atts));

Also, when corrected, still shows the time, not the date

Comments are closed.