Using shortcodes in WordPress

Shortcodes are an easy way to add dynamic information to a post or page without the need to type any HTML. In this example, I’m going to show you how to add a button to a page.

Normally, you’d type something like the following:

<a href="/contact/" class="btn">Get in touch</a>

And, with a bit of CSS, we get this:

button

With shortcodes, we could achieve the same result by typing something like this:

[button]Get in touch[/button]

Creating a shortcode requires a little bit of PHP knowledge. Place the following code in your functions.php file in your theme:

The code above is relatively simple. We create a function (I’ve called it shortcodeButton) and pass the variables $atts and $content. In the function, we return the HTML for our link. I’ve hard-coded the link to go to a contact page. Notice how we use $content – this pulls the text from our shortcode above, in this example ‘Get in touch’. We finally use add_shortcode to link our function to the shortcode tag. We can extend this further. Lets say that we want to change where the link goes and what colour it will be. You can pass parameters, so to do this we can amend the function like so:

We’re now making use of the $atts variable using the extract function. I’ve defined two: link and colour and set the defaults (so, on line 4, I’ve set the default colour to green). We then use {$link} and {$colour} to return these values.

That means we can now add a custom link, like so:

[button link="/contact/" colour="blue"]Get in touch[/button]

And this would output the following HTML:

<a href="/contact/" class="btn btn-blue">Get in touch</a>

This is a basic example of how to use shortcodes. It’s a powerful feature with lots of potential and it has the added benefit that clients find it easier than writing HTML.

Related articles

My writing, your inbox

Join hundreds of freelancers & creative professionals who receive my twice-monthly newsletter about business, productivity, creativity, writing, and more.

No spam, promise. Unsubscribe at any time.