How to Create Shortcode in WordPress step by step

0 101

In WordPress, Shortcode is a feature to insert content into a post or a page programmatically. Shortcode will work if it is specified inside a page or post content. Otherwise, we have to add the do_shortcode hook to use a shortcode outside the content. In a previous WordPress tutorial, I have used shortcode feature to insert advertisement banner into a post. WordPress introduced the shortcode feature from version 2.5 and since then creating macros in post’s content became simpler.

To add a shortcode in a WordPress page or post, we have to specify it as shortcode-name inside the content area. Then we need to create the shortcode hook into the theme. This hook specifies the shortcode name and a callback function which returns the content to be replaced for the shortcode. WordPress provides a list of built-in and additional shortcodes like, audio, caption, embed, gallery, and more.

How to Create Shortcode

WordPress shortcode API allows us to create our own custom shortcode for a post or page content. The add_shortcode() function is used to create custom shortcode. This function requires two parameters, the name of the shortcode and a callback to return content for the shortcode tags.

Add the following code in the theme’s functions.php as a hook. The callback function returns HTML content and replaces the shortcode tag you specified in your post content.

How to use the Shortcode

In WordPress, shortcode can be specified in various ways. Shortcode API supports both stand-alone and container tags. These are also called as self-closing tags and enclosing tags, respectively.

The simple usage of the self-closing shortcode tag for our custom shortcode is,

Shortcodes tags can also set attributes to the callback function in the shortcode hook. Based on this attributes we can have conditional shortcode.

The callback function returns HTML based on the attribute set with the shortcode. In the above shortcode, the ‘share’ attribute is set as false. So the callback will not append the ‘share link’ with the output HTML.

Enclosing shortcode tags allows us to pass content to the callback function. The following code shows how to use enclosing shortcode.

The example PHP code in the shortcode container is sent as the content of the callback function. The callback function returns prettified source to the WordPress post or page content.

 

You might also like More from author

Leave A Reply

Your email address will not be published.