How to create WordPress shortcodes

So today we’re going to learn how to take our code snippets and turn them into handy, dandy little shortcodes.

Shortcodes are one of the coolest features of WordPress from a content creator’s perspective. They allow users to execute code segments beyond what the WYSIWYG editors can handle, keep the code consistent site wide, make things far more concise, all while editing and not having to live in fear of their code getting stripped out or boggled up when editing later. All good things.

Functions.php or plugin?

An old discussion of course. Ultimately it comes down to whether you want the shortcode to depend on the theme or not. Will you be using this shortcode on other projects? Could it be useful with a different theme? It takes almost the same amount of time whichever you choose and each will work just as well for the current project.

Let’s make a shortcode

I’m going to use a bunch of examples of actual shortcodes that I have created for recent projects.

Shortcode 1: Output string


//[op] outputs the phone number
function our_phone() {
 return "(269) 588-0556";
}
add_shortcode('op', 'our_phone');

This code will allow me and all the other authors on this site to not have to remember our phone number and also change it globally if we needed to. This was handy on a recent project where there were multiple authors on the site and multiple phone numbers. Making a shortcode like this for each one made it easier for authors put the number into their content without looking it up each time and also allowed us to change the number everywhere when we wanted to by just changing the shortcode.

Shortcode 2: Output current month


//[month] shortcode. Outputs current month.
function kjm_month() {
$kjm_date=getdate(date("U"));
return "$kjm_date[month]";
}
add_shortcode( 'month', 'kjm_month' );

This shortcode came in handy for my team because several authors were frequently writing promotional pages on the site and often the promotions were similar from month to month so this shortcode allowed them to automatically output the current month in their copy. This way they didn’t have to go back on the first of each month and update every single page that contained a monthly promotion.

Shortcode 3: Countdown timer


//[cdt] countdown timer shortcode
function content_countdown($atts, $content = null){
 extract(shortcode_atts(array(
 'month' => '',
 'day' => '',
 'year' => ''
 ), $atts));
 $remain = ceil((mktime( 0,0,0,(int)$month,(int)$day,(int)$year) - time())/86400);
 if( $remain >= 1 ){
 return $daysremain = "$remain";
 }else{
 return $content;
 }
}
add_shortcode('cdt', 'content_countdown');

Now we’re getting to a shortcode with attributes. This snippet is an only slightly modified version of one created by Kevin Chard at WPSnipp. What my version does, is it shows the number of days remaining before a specified date. This was also very handy for the authors on this site who would run monthly promotions which had an end date, and this allowed them to automatically display to the site’s visitors how many days remained before the offer would expire.  The purpose was to give a sense of urgency and drive sales.

But what’s going on inside these shortcodes

Let’s take just a second to explain some things:

  • When outputting data we always use return whereas in many normal programming instances we would use echo. Using echo will usually return some funky results.
  • The add_shortcode() function accepts two parameters. The first is the shortcode you want to create (the word(s)/phrase you enter in the square brackets) and the second is the function that it will execute.
  • Best practice for your shortcode names and attribute names would be lowercase.

There are truly thousands of things you could do with shortcodes. I greatly appreciate the ability to condense code snippets and re-use them endlessly. On a different project I took a complicated archive page on a website that had hundreds of lines of code and brought it down to four lines with massive improvements.

Here are a few ideas of what you can do with shortcodes:

  • Output strings of text
  • Make buttons
  • Create forms
  • Implement social sharing buttons
  • Embed videos
  • Embed tweets
  • Embed Facebook status updates
  • Show featured posts
  • Show featured products
  • Include custom javascript
  • Create HTML elements (tables, divs, sections, etc.)
  • Insert media
  • Insert photo galleries
  • Display countdown timers
  • Display user count
  • Display comment count
  • Insert animated sliders
  • Include interactive calculators
  • Many many many more!

I’d love to learn about what shortcodes you have created or would like to create. Share in the comments below.