Shortcode Tutorial – Steps to Create Shortcode

WordPress shortcodes are square bracket strings ([ ]) that magically transform into something fascinating on the frontend.

Creating shortcodes in WordPress is very easy. You need to follow these simple steps.

  • Create a function in wordpress by means defining into functions.php of activated theme or inside any custom plugin. This function will be called by shortcode.
  • Register shortcode by putting a unique name of that.
  • Bind registered shortcode to created function.

Let’s create a simple basic shortcode with a message to print when calls.

We will create shortcode by creating a custom plugin.

Adding comments to plugin and add function to it.

Create a folder simple-basic-shortcode inside /wp-content/plugins folder.

Next,

Create a file simple-bs.php inside it. Open and write this code into it.

<?php

/*
Plugin Name:  Simple Basic Shortcode
Description: It displays a message with current date
Author: Online Web Tutor
Author URI: https://onlinewebtutorblog.com/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: basic-shortcode
Version: 1.0
*/

Add Function into Plugin

function owt_sms_call()
{
    return "Hi, this is sample plugin " . date("Y-m-d");
}

Register Shortcode

To register shortcode in wordpress, we use a wordpress function add_shortcode(). About this function we will learn more in next tutorial. We can find more details of this inside /wp-includes/shortcodes.php

add_shortcode('owt_sms', 'owt_sms_call');

owt_sms is the name of shortcode. Keep in mind this must be unique. owt_sms_call is the name of function. When we call owt_sms shortcode, attached function owt_sms_call will be called.

Here, is the complete code of plugin.

Complete Plugin code

<?php

/*
Plugin Name:  Simple Basic Shortcode
Description: It displays a message with current date
Author: Online Web Tutor
Author URI: https://onlinewebtutorblog.com/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: basic-shortcode
Version: 1.0
*/

function owt_sms_call()
{
    return "Hi, this is sample plugin " . date("Y-m-d");
}

add_shortcode('owt_sms', 'owt_sms_call');

You will see inside Plugins >> Installed Plugins

Activate this plugin to use.

In your post/page you can use this shortcode.

[owt_sms]

It will output

Hi, this is sample plugin 2021-12-18

Successfully, we have now idea about creating a basic shortcode. The shortcode we have created is self-closed shortcode.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more