Why do we need shortcodes and what can we do it them? Well, we need them because we can reuse them all over the say and we can make them output whatever data we want.

Besides what we said above, many of the custom functionalities built by developers use shortcodes. So next time you see a fancy slider or a cool calendar inside a post keep in mind that behind it you might find a shortcode.

So let’s get down to business and create one simple shortcode.

Your first WordPress shortcode

First, a shortcode looks like this: [my-awesome-shortcode]. Basically is a set of parameters between square brackets.

So to quickly define a shortcode we’re going to use the functions.php file of a theme. You can basically add anything inside there.

So we will define a simple function which returns a string message and also register it as a shortcode.

PHP

Now if we add a new post and add the shortcode inside it using the Gutenberg’s shortcode block, we will see the message “My demo shortode” when we will visit that post.

Passing attributes to a shortcode

How about passing attributes to a shortcode? For example instead of a string we can return a html heading. Let’s change our shortcode function to do that.

PHP

So now our shortcode will output a H1 heading. But we can make the text dynamic so we can output whatever we want by passing it an attribute variable and using the shortcode_atts() function to parse the attributes and set some defaults in case they are not present.

PHP

Now if we simply use our shortcode like this [my-awsome-shortcode] it will output by default the H1 heading using the “My awesome shortcode” message, but if we pass it a title attribute like so [my-awesome-shortcode title=”Hello there”] it will output the H1 heading using our given title.

Using shortcodes inside PHP

Shortcodes are not meant to be used specifically in the WordPress’ text editor. You can use them inside your PHP code as well (for example in your themes or plugins).

To use shorcodes in PHP you just wrap them inside the do_shortcode() function. Let’s have a quick example.

PHP

Note that my shortcode function already does “echo” inside it instead of “return” so that’s why i’m not using “echo do_shortcode(…)”. Sometimes, when you use shortcodes only internally (inside PHP), you might want them to always return something instead of echoing out the output.

As an end note, keep in mind that shortcodes can be used for an infinite number of reasons and can be really helpful.

Leave a Reply