WordPress introduced shortcode since version 2.5. Create custom WordPress Shortcode is a specific code that lets you do to set functions for creating code with very little effort. Shortcodes can embed files or create objects that would normally require lots of complicated.
WordPress Shortcode inserted into post, page and other content, it means to instruct WordPress to call macro code by using a trivial shortcode square brackets [mygallery] and Shortcodes can also be used with additional attributes [mygallery id=”123″ size=”medium”]
In this tutorial, we will talk a bit more about how to create custom WordPress Shortcode plugin. Then, we’ll show you how simple it can be to program your own in the following steps. Let’s get started!
Contents
Step 1: Create Shortcode Function
First, go to directory wp-content → themes → your active theme name then open up with your favorite text editor a function.php file of the active theme. Create or write new php function with a unique name which will execute the code you’d like the shortcode to trigger.
<?php
function hozbit_shortcode() {
return 'Hello hozbit...!!!';
}
?>
This function can also take custom parameters, if you want custom to add a parameter into the function, you might add an attribute parameter. These parameters are called attributes, and they are all handled using a single array predefined as $atts by WordPress.
<?php
function hozbit_shortcode( $atts = NULL ) {
$a = shortcode_atts( array(
'name' => 'world'
), $atts );
return 'Hello ' . $a['name'] . '!';
}
?>
This defaults the name attribute to world if attibute null value. If a name is provided, the function will output that instead. Shortcode square brackets as the following.
[helloworld]
Shortcode square brackets with attribute parameter
[helloworld name="hozbit Team"]
Step 2: Register Shortcode Function
The last step is to register your new shortcode with the Shortcode API. This is done with the add_shortcode function. It requires two arguments:
- The shortcode tag to be used within the text editor
- The name of the function handling the execution of the shortcode
Beneath your shortcode function, include this line of code and update it to match your own values:
add_shortcode('helloworld', 'hozbit_shortcode');
The first value will go within square brackets in the text editor. The second will match the function name you wrote in the previous two steps. Both should be unique enough so they don’t interfere with other shortcodes included by WordPress core, themes, or plugins.
Step 3: Use WordPress Shortcode
Once you have finished, here the example to insert a shortcode square brackets into the WordPress editor.
If this article Create custom WordPress shortcode plugin could help you, please rate above Star button rating and share to help others find it! Feel free to leave a comment below.
No Responses