How to create a custom Shortcode in WordPress

Shortcode in WordPress are text macros which are used in content area of a Page or Post and May be Widgets. Shortcodes are created by using a collections of functions. You will learn about shortcode and How to create a custom shortcode as you proceed.

What is a Shortcode?

Shortcode are text macros or shorthand tags, which can be used in post or pages to display some codes or some custom texts.

syntax :

Shortcode can be of two types: Self closing and enclosing. Shortcodes can have attributes too.

Self closing: [myshortcode]

Enclosing: [myshortcode] Some text [/myshortcode]

With Attributes: [myshortcode att1="name" att2="phone"]

Build in Shortcodes in WordPress :

There are some build in Shortcodes which are using to display gallery, audio. video etc.

Creating a custom Shortcode

There are two component of a simple shortcode a shortcode tag and a callback function as shown below.

a. Create a simple self-closing Shortcode.

Here myshortcode is shortcode tag and myshortcode_func() is callback function. This code block may either be included in active theme functions.php file or as a standalone plugin.

b. Create a self-enclosing Shortcode with attributes.

Here myshortcode is shortcode tag and myshortcode_func() is callback function. This Shortcode support attributes to display full name. This code block may either be included in active theme functions.php file or as a standalone plugin.

If no attributes will be used, the shortcode will display default values set in f_name and l_name.

[myshortcode] will output: Full Name: Gyan Giri .

[myshortcode f_name="Sanjay" l_name="Kumar"] will output: Full Name: Sanjay Kumar.

c. Create a enclosing Shortcode.

Here myshortcode is shortcode tag and myshortcode_func() is callback function. This code block may either be included in active theme functions.php file or as a standalone plugin.

This Shortcode will wrap a span will class title to any content enclosed within the Shortcode.

Output:

[myshortcode] Hello John [/myshortcode] will output the text with span wrapped in text.

d. Create a enclosing Shortcode with attributes.

A enclosing shortcode can also have attributes.

Here myshortcode is shortcode tag and myshortcode_func() is callback function. This code block may either be included in active theme functions.php file or as a standalone plugin.

This enclosing shortcode will have option to modify class name as well as display text too.

Output:

[myshortcode classname="heading" ] Post title [/myshortcode] will output.

Troubleshooting:

Add following code to functions.php or plugin file you are developing to enable the shortcode to Text Widgets.

 

shortcode are a great functionality, When used wisely It will do Wonders.

Related posts

Leave a Comment