Creating Custom Shortcode in WordPress

With a lot of customization with the theme WordPress also provide us to create our own Custom Shortcode. Basically, shortcodes are the small piece of code which let user to add dynamic content in WordPress posts, pages or sidebar widgets. A Shortcode is simply a small text between the square brackets, like this [example]. This will display the content according to the defined function.

Creating a Custom Shortcode

To create your own shortcode you need to have some coding experience. We can write code for a shortcode in function.php of your theme file or if you are using a lot of shortcodes it’s better to have a separate file and then include it function.php file of your theme.

First, you need to create a function for your shortcode. Your function name for the shortcode should be unique so that it does not conflict any other function name.

Here my function name is demo_shortcode ()

Inside this function we will write the code that our shortcode will perform. Here we are displaying text with some style:

Now we will register our shortcode using add_shortcode function. This function accepts two parameters:

  • The shortcode tag used within the text editor.(here demo)
  • Name of the function executing the shortcode.(here demo_shortcode)

Displaying the content of shortcode

To display we use the first parameter of the add_shortcode function (demo) within the square brackets in the text editor of the WordPress. [demo] Use this in any post or pages where you want to display the content.

Custom Shortcode

Output

Custom Shortcode output

Leave a Reply