Shortcodes in WordPress
Custom Fields may come in handy if you wanted to add something to your post, but their content is always outside the actual content of a post (although inside the loop).
But what if you wanted to insert something in a post as content, for instance the result of a function?
Well, that’s where shortcodes can be used. Shortcodes are available to mortals since WordPress version 2.5, so be sure to be up to date (and not only for shortcodes!).
Take a look at my about page (you don’t have to, I will copy the relevant text here).
There’s this text:
My name is Peter. I’m 47 years of age, …
Next year when you read this, I’m not 47 anymore, but will be 48 of age. That means that I have to modify that about page for at least once a year, to update my age. Not that that’s such a problem, but I don’t want to confuse you with (or even worse: lie to you about) a false age.
If I edit that about page, the actual text looks like this:
My name is Peter. I'm [peter-age] years of age,
How does WordPress know how to translate this piece of text-between-brackets ([peter-age]) into my age?
It follows the same principle as filters and actions (used in plugins), in fact you could even write a plugin, where you define shortcodes (and I know several plugin writers have).
For my examples I will be modifying functions.php in my theme directory. You probably have a functions.php in your theme directory, and if you don’t have one, I’ll show you how to create it. There’s one drawback in using this functions.php: if you switch themes, your shortcode will not be known in that other theme. If you want to prevent that, you can follow the instructions on plugins on this site.
Your basic functions.php should look like this:
< ?php // lots of code here, or not if you created this one yourself ?> |
To use shortcodes, you need actually two things: you have to tell WordPress that the shortcode exists, and you have to tell WordPress what to do if it encounters that shortcode. this is done with the add_shortcode() function.
In my functions.php is this:
< ?php add_shortcode('peter-age','calc_my_age'); ?> |
This snippet tells WordPress that if it stumbles over [peter-age], it should call function calc_my_age(); So the only thing to do is to define that function.
< ?php function calc_my_age() { return "43"; } add_shortcode('peter-age','calc_my_age'); ?> |
That’s it. We’re done. We’ve created a shortcode. Till next time.
No wait, that would be too easy, since I would have to modify that function annually, and that would be even more cumbersome than modifying the post itself. I’ll carry on.
One note though: although you could ‘echo’ the value back to the post, changes are that your layout would get messed up (if I recall correctly the place where that ’43′ would show up isn’t even defined), so always use ‘return’.
Let’s create a useful function, that actually updates my age as it evolves (or as I evolve, or age).
< ?php function calc_my_age() { // define the dates $now=strtotime("now"); $birthdate=strtotime("24 August 1966"); $lengths = array("60","60","24","7","4.35","12","10"); $difference = $now - $birthdate; for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { $difference /= $lengths[$j]; } $difference = intval($difference); return $difference; } add_shortcode('peter-age','calc_my_age'); ?> |
Although there are definitely easier ways to calculate ones birthday, I translate both dates (the current one on $now, and my birth date in $birthdate – now that you know: congratulations are welcome in August
) in unix timestamps (seconds since Epoch), calculate the difference, and divide the number by seconds, minutes, hours, days, etc. The outcome of these divisions is my age in real, and I take the part before the decimal separator. That’s my age (47).
I have to tell you a small secret: it’s not only the about page I don’t want to update, but also this article. So somewhere at the top, I included this text in the post:
Next year when you read this, I'm not [peter-age] anymore, but will be [peter-age modifier="1"] of age.
Notice the second call to shortcode, especially the ‘modifier’ thingemy? It’s possible to call shortcodes with parameters, and here I tell this shortcode to pass the value ’1′ to the function. Also notice that the first call has no such parameter, so it’s possible to define a default value.
Here’s what my function looks like:
< ?php function calc_my_age($atts) { // give $atts a default value extract(shortcode_atts(array( 'modifier' => "0", ), $atts)); // define the dates $now=strtotime("now"); $birthdate=strtotime("24 August 1966"); $lengths = array("60","60","24","7","4.35","12","10"); $difference = $now - $birthdate; for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { $difference /= $lengths[$j]; } $difference = intval($difference); $difference = $difference + (int)$modifier; return $difference; } add_shortcode('peter-age','calc_my_age'); ?> |
So what happened? First of all, the function is called with a parameter, and the function has to know you’re passing parameters to it.
function calc_my_age($atts){} |
Next, I want to give the parameter ‘modifier’ a default value.
// give $atts a default value extract(shortcode_atts(array( 'modifier' => "0", ), $atts)); |
I want my age not to be modified when I pass no modifier, although it would be nice to get a few years off (who am I kidding?).
And a bit further I add the value of modifier to the difference:
$difference = $difference + (int)$modifier; |
That simple. You can even pass more parameters to shortcodes, if you wanted to ([peter-age modifier="-10" hair="yes"])
.
But you can do more with shortcodes.
Suppose you wanted to embed some words in your post in strong, italics and red text, and you do that quite often, wouldn’t be nice to have some shortcode (!) for that?
I mean, suppose you wanted to type your text like this:
This is [special]very special[/special] text, looking like this: This is very special text
This is also possible with shortcodes.
Let’s see how the function would look like:
< ?php function my_special_text($atts, $content=null) { return '<span style="color: red;"><strong><i>' . do_shortcode($content) . '</i></strong>'; } add_shortcode('special','my_special_text'); ?> |
If we want to embed content in shortcodes, then we actually must (yeah, I used the shortcode here) pass two parameters to the function we call, the second one being the $content parameter, although we do not have to use the first one.
In short we return the content, surrounded by some extra text, in this case some xhtml tags. The do_shortcode() function makes it possible to actually embed shortcodes, just like you would embed xhtml.
[a]
[b]
[c]
[/c]
[/b]
[/a]
You might recognize BBCodes here
That’s all for now. You can do this, and much more with shortcodes. Enjoy your shortcodes.
This entry was posted on Friday, October 23rd, 2009 at 7:09 pm and is filed under webpublishing. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Putting this right in the theme’s functions.php never occurred to me. This was a great walk-through. Thanks
Thanks for your comment.
In fact, anything in plugins can be in your functions.php. But you got me thinking:
Since the shortcodes are used in the posts, and therefore theme independent, they are better to be put in a plugin.
Followed you here from the LinkedIn WP group. This is a great tutorial! I can’t wait to try it out. Thanks for sharing!
Just don’t forget to alter my age into your own
Thanks for your comment.
Thanks for sharing, great tutorial!
Yeah, I’m with Mark – great tutorial!
Loved the calculating age shortcode……I was trying to figure out how davidgagne.net got his updating footer. Solved!!
Thanx again….