Shortcode Tutorial – Create Enclosed Shortcodes

Enclosed Shortcodes, is a type of wordpress shortcodes that has a start tag and an end tag, just like an HTML tag. These shortcodes allow us to embed content within shortcodes. Also we can pass values into it.

Syntax

[shortcode_name] Content to be displayed [/shortcode_name]

Example

[caption] <image> Caption [/caption]

[embed] Your Content [/embed]

Crate a custom self-closed shortcode

We will create self-closed 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 will display message into h2 tag
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_basic_shortcode_text_heading($attr, $content)
{
    $heading = "<h2>" . $content . "</h2>";

    return $heading;
}

Register Shortcode

To register shortcode in wordpress, we use a wordpress function add_shortcode().

add_shortcode('h2_text', 'owt_basic_shortcode_text_heading');

h2_text is the name of shortcode. Keep in mind this must be unique. owt_basic_shortcode_text_heading is the name of function.

When we call h2_text shortcode, attached function owt_basic_shortcode_text_heading will be called.

Here, is the complete code of plugin.

<?php

/*
Plugin Name:  Simple Basic Shortcode
Description: It will display message into h2 tag
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_basic_shortcode_text_heading($attr, $content)
{
    $heading = "<h2>" . $content . "</h2>";

    return $heading;
}

add_shortcode('h2_text', 'owt_basic_shortcode_text_heading');

In your post/page you can use this shortcode.

[h2_text]Sample content[/h2_text]
[h2_text]Test content[/h2_text]

Output

Successfully, we have now created enclosed shortcode in wordpress. In the next tutorial we will see how to work with parameters and enclosed 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