Home » Source Book » What is Shortcode and How to Use Shortcode in WordPress

What is Shortcode and How to Use Shortcode in WordPress

Last updated on May 30, 2020 by

Table of Contents
1. What is Shortcode
2. How to Write Shortcode
3. Built-In Shortcodes
4. How to Create Shortcode
5. How to Use Shortcode

We can easily extend the site functionality without repeating ourselves with the help of a shortcode. Nowadays, most of the plugins provide the shortcode functionality for better reusability. So the question is what is shortcode in WordPress? So, let’s start by exploring the basics of shortcodes!

What is Shortcode

The shortcode definition varies in different people. We define it as like shortcode is a WordPress feature that helps you to overcome your repetitive task with very little effort.

Another simple definition: Shortcode is a short name of your bunch of a function’s code which allows you to execute anywhere in WordPress by just calling that short name.

How to Write Shortcode

A shortcode is written inside two square brackets. For example, the "[sc_show_gallery]" shortcode can be used to add a photo gallery of images to any page, post, or any other places in WordPress.

Built-In Shortcodes

[audio]
[caption]
[embed]
[gallery]
[playlist]
[video]

We can also pass attributes into the shortcode as the following example shows:

[gallery id="77" columns="4" rows="2"]

How to Create Shortcode

As the name suggests add_shortcode() function is used to add the shortcode in WordPress. It accepts two parameters. The first parameter is the name of the shortcode and the second parameter is a callback function’s name.

Syntax: add_shortcode( 'name of shortcode', 'callback function name' );

Example of the shortcode:

function dynamic_copyright_year(){
    return date('Y');
}

add_shortcode('copyright_year', 'dynamic_copyright_year');

On the above example, we have created a copyright_year shortcode that will print the current year when the shortcode executes. Let’s run the shortcode.

How to Use Shortcode

A do_shortcode() function is used to run/execute the created or built-in shortcode. As we have seen above that shortcode written inside two square brackets so here we have to use two square brackets while executing.

Syntax: do_shortcode( '[name of shortcode]' );

Example:

echo do_shortcode('[copyright_year]');  // This will print current year.

We hope this article helped you to understand the basic concept of shortcode in WordPress.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂

Leave a Comment