How To Create Shortcodes In WordPress

Last Updated on September 21, 2022 by 53 Comments

How To Create Shortcodes In WordPress
Blog / Tips & Tricks / How To Create Shortcodes In WordPress

WordPress introduced the shortcode API six years ago with the release of WordPress 2.5. Shortcodes are now used by a large number of WordPress plugins to allow users to add content to their posts and pages.

The shortcode API allows you to create your own shortcodes by adding functions to your theme functions.php template (this is located at www.yourwebsite.com/wp-content/themes/yourtheme/).

In addition to creating your own shortcodes, WordPress also includes five default shortcodes with the WordPress core:

  • audio – Allows you to embed audio files.
  • caption – Allows you to wrap captions around content. It is commonly used with images.
  • embed – Allows you to embed a wide range of content such as video, audio and tweets.
  • gallery – Allows you to insert image galleries.
  • video – Allows you to embed video files.

Although the default WordPress shortcodes are commonly used, very few WordPress users take advantage of the shortcode API and design unique shortcodes for their website. In this tutorial, I would like to show you how straight forward it is to enhance your website with custom shortcodes.

Before you begin, please make sure you make a backup of functions.php and any other files you edit before making changes with your live website.

Creating a Shortcode – A Basic Example

shortcodes-2

To give you a good understanding of how the WordPress Shortcode API works, let us start with a basic shortcode function.

Please remember that shortcodes should be created for content and functionality that you use frequently. The whole point of using shortcodes is to save someone time. If you are only going to use something once, there is not much point in creating a shortcode for it.

I write around a dozen articles per week. One thing I do frequently is encourage those who enjoyed my articles to subscribe to my blog (or the blog I am writing for). I presently write this out every time, however I could save myself a lot of time by creating a shortcode for the text.

To do this, I could add a function such as this to my theme’s functions.php template:

// Function to add subscribe text to posts and pages
  function subscribe_link_shortcode() {
    return 'If you enjoyed this article, I encourage you to <a href="http://feeds.feedburner.com/ElegantThemes" title="Subscribe to Our Blog">subscribe to the Elegant Themes blog via RSS</a>.';
}
add_shortcode('subscribe', 'subscribe_link_shortcode'); 

Those of you who have no coding experience may find the above code a little daunting, however it is easy to understand once you break the code down line by line.

The first thing we do is add a comment above our function. This will help us quickly see what our function is for when we view the code at a later date.

// Function to add subscribe text to posts and pages

We then define our function. I like to use names that are self-explanatory, so I have called my function “subscribe_link_shortcode”.

function subscribe_link_shortcode() {

Next, we define our message. The return statement will display our message when it is called. It also stores the messages (as opposed to echo, which will print it but not store it).

return 'If you enjoyed this article, I encourage you to <a href="http://feeds.feedburner.com/ElegantThemes" title="Subscribe to Our Blog">subscribe to the Elegant Themes blog via RSS</a>.';

The function is then closed.

}

We then define the shortcode itself using the add_shortcode function. The first variable specified defines the shortcode to be used and the second variable calls our function (i.e. the one we defined above).

add_shortcode('subscribe', 'subscribe_link_shortcode'); 

After saving the functions.php template, we can now call our message whenever we want using the shortcode subscribe.

[subscribe]

Using the subscribe shortcode in a post or page will produce the following message:

If you enjoyed this article, I encourage you to subscribe to the Elegant Themes blog via RSS.

I used a simple message in my example, however you could modify this to display many other things. For example, you could create a shortcode for displaying adsense advertisements or a subscription form for your newsletter; and then insert them anywhere you want in your articles.

Creating a Shortcode With Attributes

shortcodes-1

Attributes can expand the functionality of shortcodes by allowing you to pass data through your shortcodes.

In the example below, I will show you how attributes can be used to expand the function we created earlier. As you can see, much of the code remains the same.

// Extended subscription function with subscription type variable
function subscribe_multilink_shortcode( $atts ) {
    extract( shortcode_atts( array(
        'subtype' => 'RSS',
        'subtypeurl' => 'http://feeds.feedburner.com/ElegantThemes',
    ), $atts, 'multilink' ) );
 
    return sprtinf( 'Be sure to subscribe to future Elegant Themes updates <a href='%1$s'>by %2$s</a>.',
    	esc_url( $subtypeurl ),
    	esc_html( $subtype )
    );
}
add_shortcode( 'subscribe', 'subscribe_multilink_shortcode' );

$atts is the name of our attribute array. We then use the extract function to import variables from our array (via the shortcode_atts WordPress function).

Two attributes are then defined: subtype and and subtypeurl. These represent the type of subscription and the subscription URL. These attributes are then called in our message.

Our default subscription type is RSS and our default subscription URL is http://feeds.feedburner.com/ElegantThemes. This information will be displayed when no attributes are defined.

Therefore, when you add the following to a post:

[subscribe]

We will get the following output:

Be sure to subscribe to future Elegant Themes updates come packaged with shortcodes that make publishing beautiful content easy. The shortcodes can be used to create slideshows, columns and tables. It even allows you to password protect your content.

I hope you have enjoyed this tutorial on creating a unique shortcode for your WordPress website. If so, I encourage you to subscribe to Elegant Themes as we have some great content in the pipeline 🙂

Also, once again, I remind you to back up any files before you edit them.

Divi Anniversary Sale

It's The Divi Anniversary Sale! Save Big For A Limited Time 👇

Save big on Divi and Divi products for a limited time.

Access The Sale
Divi Anniversary
Premade Layouts

Check Out These Related Posts

Splice Video Editor: An Overview and Review

Splice Video Editor: An Overview and Review

Updated on March 10, 2023 in Tips & Tricks

Video is a valuable form of content for social media. Unfortunately, creating quality videos is usually a long process that involves moving mobile footage to a desktop app for editing. However, mobile editing is on the rise. Apps such as Splice Video Editor make it possible to efficiently create...

View Full Post
How to Use Font Awesome On Your WordPress Website

How to Use Font Awesome On Your WordPress Website

Updated on September 16, 2022 in Tips & Tricks

When given the choice between using a vector icon or a static image, it’s a good idea to go with the vector. They’re small and fast to load, and they can scale to any size without a loss of resolution. Font Awesome is a superb library of vector icons that you can use on your websites,...

View Full Post

53 Comments

  1. Hi, thanks for the tut, I know it’s old, but there’s a small typo :
    sprtinf() instead of sprintf().

    Thanks again.

  2. Hi

    how do I define shortcode not from within a theme (i.e. not from within a theme’s functions.php file)? Your example work fine, as long as I keep the same theme, but I wonder whether there is a way to define it from within a plugin folder instead?
    thanks best wishes mario

  3. Seems the esc_html in Divi’s shortcode for CTA button prevents the ability to place the required html inside the button’s label.

    also

    Shortcodes inside shortcodes don’t work for Divi’s buttons with the font-awesome shortcode plugin.

  4. Okay, sorry for all these comments, but I tried it again, using the shortcode directly in a post (instead of in the single.php template), and had the same result. The link embedding does not work. So, back to my original question: Did something change in the new WordPress release to cause this? Or, am I doing something wrong? Thanks.

  5. The html for embedding a link isn’t working. The text just appears as ‘<a href=' etc. I tried using your code as you show it exactly, to make sure I wasn't making some mistake, and had the same result. I am using the html substitutes for the brackets, etc, as you showed ([ etc), and they work as far as displaying an angle bracket, etc, but the link embedding does not work.

    Did something change in the new WordPress release to cause this?

    • I figured this out and thought I’d post here in case anyone needed help. Make sure the coding is not “escaped” as it is in the example. I thought it had to be as the example had it that way, but if done that way it was just showing the coding. A much better tutorial I’ve found is this one: https://www.nosegraze.com/create-own-wordpress-shortcodes/

  6. Woderful tutorial.Anyone can understand easily. Great Job!!!

  7. I uploaded this directly to my child theme folder and everything disappeared.

    I’m using Divi theme. So I read the child theme post on this blog as well and it didn’t mention if I had to install via zip or not so I deleted the functions.php and restored site, then I tried it via zip method and installing the child them again after deactivating it- again everything disappeared again.

    Here is my functions.php
    <?php
    // Function to add Custom CTA
    function custom-cta() {
    return 'Learn the many benefits todaySchedule a DemoContact Us‘;
    }
    add_shortcode(‘CustomCTA’, ‘custom-cta’);
    ?>

  8. Highly functional
    Thanks very much to Mr. Muldoon

    یک مقاله خوب برای توسعه دهندگان وردپرس.
    A good article for WordPress developers.

  9. ElegantThemes is awesome, and I’m digging the Divi theme. I’m using it for a couple of websites. Do you have a framed image shortcode meaning do you have a shortcode that adds padding, white background, and maybe a border? That would be great if you guys created that shortcode.

    • You could do this very easily using CSS by just adding a basic class to your stylesheet 🙂

  10. i use plugin Lizatom Shortcodes. It is very good. I recommend use it

  11. I am currently using the divi theme. I am having trouble using the WP manic action boxes, and also I can’t get amazon affiliate links to show the pictures. Are there tutorials for this?
    Thanks
    Bob

    • I haven’t used Divi myself, so cannot help with you that.

      Your problem with Amazon links seems to be an HTML image. I recommend reading a good tutorial on HTML. Specifically the sections about anchor tags and image tags (i.e. a & img).

  12. Can you explain what you mean by return (vs echo) storing messages?

    Next, we define our message. The return statement will display our message when it is called. It also stores the messages (as opposed to echo, which will print it but not store it).

    Not familiar with this distinction.

    Also, typographical error in your code: sprtinf (should be sprintf)

    Thanks

  13. my client wants social sharing buttons in only a few places on some pages; using Divi theme. He doesn’t want anyone leaving the page by clicking though. I am not a developer so if anyone has something for me or point me in the right direction, thanks. Peter

  14. Thank for this fully explained tutorial on creating wordpress shortcodes. Is there any chance that ElegantThemes add all the shortcodes that are available in Shortcodes Ultimate Plugin. Or at least most of those.

    • I don’t forsee that happening.

      And in any case, it is more practical to use a plugin for shortcodes incase you change theme 🙂

  15. Kevin, it is a great tutorial for a new blogger like me. Surely I’ll create few shortcodes for my own blog. Thanks for the share.

    • No problem Lakhyajyoti

  16. The first start for novice users would be to use the shortcodes that Elegant Themes already provide in the themes, remebering of course that the first function of a website is to sell the owners business proposition and not simply to showcase web designers flair.

    • Very good point Ray. All Elegant Themes designs feature shortcodes.

  17. Cheers, very helpful

    • No problem.

  18. Thanks for the article. Useful for developers like me.

    • You’re welcome.

  19. Great article! I have never come across this kind of information before and always thought that shortcodes only came with the theme. Never knew I could create my own. Also, thanks for explaining how to create shortcodes in a way that is easy to understand and follow.

    • No problem Greg. Glad you found it useful 🙂

    • extract() hasn’t been deprecated as your post eludes (though there is a very old post on trac that is working towards it). In fact, it’s still used in core, and Kevin’s example of using the function is taken straight from the WordPress codex entry on shotrcodes (which is probably why he included it):

      http://codex.wordpress.org/Shortcode_API

      It’s true that extract() can make tracking your variables more difficult, and you may wish to avoid it. I think I will leave this post as it is to avoid confusion, though I think you are right that not using extract() has its benefits.

        • The ticket exists on trac, but it’s a year and a half old and isn’t yet set to make it to core. You can certainly avoid extract() if you wish. We took our example from the WordPress codex on the shortcode API.

  20. Thanks again for the amazing tutorial! Very helpful. Possibly one for adding footer menus in the future?

  21. thanks for this great tech tutorial however, how can you style the shortcode made to give visually appealing icon/graphics?

  22. Excellent tutorial, Kevin, as usual.

    For those of us who are code-challenged, there is this wonderful plugin which makes things a lot easier and does not require editing functions.php.

    http://wordpress.org/plugins/post-snippets/

    Only use it with html snippets though, as using it with php snippets may create a security risk. You can still have attributes though, as if you were working with php.

  23. What an awesome, straightforward tutorial! Thank you for this. I’ve often wondered how to create a new shortcode, and now I can’t wait to try it. You make it look EASY.

  24. Very good article and at the right time. I have a client who needs HTML tables generated automatically with minimal text. After generation he can fill in all he wants or change the minimal text.

    Now, with your help from this article, I can make a shortcode with attributes for rows and columns. More than that I can add an attribute for table width.

    Oh, yes! Thank you very much, Kevin. Now I can solve a real problem for non-html users.

    How hard is to insert a shortcode in the editor?

      • I don’t know how I missed this one. Michel, thank you for your suggestion. I’ll give it a try.

  25. What a wonderful post! Great job, wonderful contribution to your community.

  26. Thanks for this … and other fine articles recently. You have really stepped up your communication game… and I appreciate it… as I’m sure thousands others do.

    You know what would be a great shortcode for you guys to add to the Elegant themes shortcode plugin?

    A nicely styled “Pull Quote”

    So that our blog posts can have more visual impact

    Anyways… thanks again for all the great new, highly useful blog posts.

  27. I did not know this. This is great. Thanks so much for keeping us up to date with all these great resources.!

  28. I love this post, please do more technical posts like these. I’ve been trying to find a good walk through for WP shortcodes to help me remember, this was perfect.

    • I’m with you on that one @Brandon
      I’d love to see something on editing the Elegant Themes footer.php to modify and add the links in there.

  29. Does Divi also include the shortcodes that you referenced or are they different? If different, is there a documented list like the one you referenced for Divi?

    “…All Elegant Themes designs come packaged with shortcodes…”

  30. are you going to release new themes in near future?

    • Of course, we are always working hard on our themes. Right now, we are doing a big round of bug fixes, after which we will be focusing on Divi 2.0. After that, you can expect some brand new themes to be released 🙂

      • Got an ETA on Divi 2.0? September? Sooner? Later? Something so I don’t keep checking daily and eventually give up waiting altogether out of sheer frustration in waiting.

      • Hi Nick,

        Please consider adding the slider from the ‘Modest’ them – is it ‘Nivo’? (ref: http://www.elegantthemes.com/demo/?theme=Modest ) . It is by far, the coolest slider I’ve seen.

        Or allow the usage of different shortcodes to use all the different type of sliders at ETT.

        Thanks!

      • Look forward to Divi 2.0 Nick.
        Got to be the theme to beat in 2014.

      • Remember add Aweber API for capture leads.

        Thank and good work. Divi is great…

      • Absolutely Brilliant news Nick, bug fixes are so so important to existing themes.( Please give explorable loving in the responsive modes )

        Loking forward to Divi 2.0 and beyond.

        Great article Kevin, I am so going to be using this, got a stack of automation needed for a massive project I have on at the moment.

Leave A Reply

Comments are reviewed and must adhere to our comments policy.

👋 It's The Divi
Anniversary Sale!
Get The Deal
Before It's Gone!
Get Started With Divi