search ]

Quick Guide for Creating WordPress Shortcodes

It is reasonable to assume that all of us have had to use these shortcodes in one constellation or another.

Generally, these come together with plugins or themes, and what they do is search and replace whenever you input something within square brackets, replacing it with any content. It can be simple text or a complex function, depending on what you’ve defined for WordPress to do with that specific shortcode.

Shortcodes that come with plugins can be very useful and significantly shorten our (or the client’s) work time, but wouldn’t it be nice if you could create shortcodes yourself? In this guide, I will show you the steps to create your own shortcodes that will help you perform certain functionalities.

Simple Shortcode

The API of shortcodes works very simply: the first thing to do is create a callback function that will run every time the shortcode is used; then, you need to associate that function with a specific shortcode and make it ready for use.

The code to create shortcodes is usually in the functions.php file, but if you plan to create many shortcodes, it might be better to write them in a separate file and include it in the functions.php file.

In the first example we’ll see, we’ll create a simple shortcode that will display some Lorem Ipsum every time you write [lorem] in the WordPress editor. As mentioned before, the first thing we’ll create is a callback function that returns Lorem Ipsum text.

Note that when creating shortcodes, we don’t print anything in the function but return some value (we don’t use echo, we use return).

function lorem_function() {
    return 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium commodi delectus dignissimos.';
}

The next action we’ll take is to register the shortcode in WordPress using the add_shortcode function. This function adds the shortcode and associates it with the function we just created.

The add_shortcode function takes only two arguments: the first is the name we choose for the shortcode (what we put inside the square brackets), and the second is the name of the function that will run when we use this shortcode:

add_shortcode('lorem', 'lorem_function');

That’s all you need to create a shortcode in WordPress.

Adding Parameters to Shortcode

Let’s continue with the same concept of similar content. Sometimes when creating a mockup, we need to add images of different sizes to our content. So, let’s create a shortcode that adds an image with a specified width and height:

[picture width="500" height="500"]

When WordPress encounters this shortcode, we want a function that inserts an image into the content.

The function should receive the width and height variables, but to cover the case where the user does not enter these variables, we will add default values for width and height. For example, we will use the service lorempixel.com to get a random image.

Let’s start by creating the callback function:

function svv_picture($atts) {
   extract(shortcode_atts(array(
      'width' => 400,
      'height' => 200,
   ), $atts));
return '<img src="https://lorempixel.com/'. $width . '/'. $height . '" />';
}

We named this function svv_picture, and since it takes arguments, we defined that it accepts the parameter $atts. To use this parameter, we need two additional functions:

  • shortcode_atts – a WordPress function that merges attributes with known attributes and fills in default attributes if required.
  • extract – a PHP function that extracts the attributes written when we use the shortcode.

Finally, the function will return the desired value. In this case, an HTML code with the img tag having the variables width and height. The only thing left is to register the shortcode in WordPress:

add_shortcode('picture', 'svv_picture');

The shortcode is ready. Now, if you add the shortcode [picture] in the WordPress editor, you will get a random image with a width of 400 and a height of 200, unless you provide different values in the shortcode.

Shortcode for Adding a Product to the WooCommerce Shopping Cart and Redirecting to the Checkout Page

If you’ve read the guide I wrote on automatically adding products to the cart using a link and wondered how to enable your customer to do this easily, here’s how.

We’ll create a shortcode that is a bit more useful than the previous examples, which inserts a link that, when clicked, adds a product of your choice to the shopping cart and redirects the user to the checkout page.

Since we explained earlier the way to create a shortcode in WordPress that accepts parameters, let’s see this without unnecessary digging. The return function will be:


function add_product_to_cart($atts) {
    extract(shortcode_atts(array(
        'id' => 0,
    ), $atts));
    $url = esc_url_raw(add_query_arg('add-to-cart', $id, wc_get_checkout_url()));
    return '"<a href="' . $url . '">Add Product</a>"';
}

To register the shortcode in WordPress, use the following function:


add_shortcode('woo_product', 'add_product_to_cart');

Now, every time you add the shortcode [woo_product id=xxx], a link will be added that, when clicked, will add the product with the ID xxx to the shopping cart and redirect the user to the checkout page.

A Few Tips on Shortcodes Along the Way

Adding a Shortcode to Text and Widget Areas

You might have thought that shortcodes are limited to posts and pages, but that’s not the case. You can use them in widget areas too. Simply add a text widget to the sidebar and insert the shortcode into it.

Note that the option to input shortcode in widgets is not enabled by default in WordPress. To enable this, you need to add the following filter to the functions.php file:


add_filter('widget_text', 'do_shortcode');

Adding a Shortcode in Template Files

If for some reason (and there are quite a few) you want to display a specific shortcode in a specific page template, you can easily do that.

Let’s say in a certain area of a page template, you want to display the shortcode of Contact Form 7. Just add the following code wherever you chose:


<?php echo do_shortcode("[example_shortcode]"); ?>

Hiding a Deprecated Shortcode

Sometimes, people change themes in WordPress and don’t realize that certain shortcodes are no longer relevant. They only notice a few months later when a visitor to their post sees some strange code in the middle of the post.

There are two ways to fix this: one is to manually remove the shortcode from wherever it is, and the other is to hide that shortcode. All you have to do is add the following code to the functions.php file:


add_shortcode('shortcodetag', '__return_false');

This code will cause the deprecated shortcode not to display anything. Don’t forget to replace shortcodetag with your shortcode name.

Conclusion

I hope this guide helped you understand how to add your own shortcodes to a WordPress site, whether for developers or for clients. If you liked the guide, I’d appreciate it if you could join the mailing list. And if you have useful shortcodes that you’ve created, share them with us! 🙂

Roee Yossef
Roee Yossef

I develop pixel-perfect custom WordPress themes, delivering high-performance, SEO-optimized websites. Have a project in mind? need assistance? Feel free to contact me!

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!