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:


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

Where to go next

1. If you'd like to discuss working together, I'd love to hear from you. Even if you don't have a specific project in mind, but would like to start the relationship for when you do, go introduce yourself.

2. If you enjoyed this article, why not share it on Twitter, Facebook or LinkedIn?

3. If you want to get my writing delivered to your inbox, subscribe to my newsletter. I only send out one email per month and you're free to unsubscribe at any time.

4. If you're on the socials, you can follow me on Twitter @marcjenkins or send a request on LinkedIn.