BLOG
How to Create a Custom Shortcode for your Website
Custom Shortcode Tutorial

Make life easier with custom shortcodes

Duplicate the same effect after coding only once

A shortcode is the WordPress way of repeating content and functionality that one uses frequently. WordPress comes with five shortcodes available by default – audio, caption, embed, gallery, and video. All of these are pretty self-explanatory, but what if you want something more specific to your own needs? Suppose you want to offer a stylized free quote on multiple pages, but not all of your pages? Or maybe you want to divide content into columns easily. Some plugins provide some functionalities, but they’re not customizable. That’s where a custom shortcode comes in handy!

A quick and easy custom shortcode example

For a detailed example, we’ll provide a step by step process on how to create a custom shortcode that returns a message that allows users to request a free quote (a la Mr. WPress). Shortcodes live in the functions.php file, so opening that in your favorite code editor is the first step. Once you’re there, here’s an example of the code to enter. (By the way, we use a shortcode to format the code like we have it below).

function request_quote_shortcode() {
   return 'For more information, please <a href="https://www.mrwpress.com/free-quote/" title="Request a Free Quote">request a Free Quote.</a>.';
}

add_shortcode('request_quote', 'request_quote_shortcode');

The function at the top is the shortcode – it will return a message with a link built in, telling users that for more information, they should request a free quote, and then directing them to a page they can do so. The add_shortcode below the function is what turns it into a shortcode – now, if we typed [request_quote] into our WordPress content area, the following would return:

For more information, please request a Free Quote.

Explore the full capabilities

This is just one, very simple instance of a shortcode. Much more complex functions or scripts could be incorporated. Oftentimes, plugins will allow you to build a contact form, and then insert it (fully functioning) into a page with just a shortcode. We also mentioned the column shortcodes we ourselves use before, which is a much more complex custom shortcode example. Those even have closing tags, the same as the shortcode opening bracket but with a slash before the name, as it affects the content in between the tags instead of acting as a standalone function. You can read more about shortcode functionality from WordPress themselves in their codex.

You can even give different styles to your shortcode content, either by giving it a class or adding in the styles right in the function. We beefed up our own free quote shortcode for the site use, instead of just simple text. Here’s a taste of what you can do with some more experience and experimenting:

Request a FREE Quote NOW!

RELATED BLOG POST