Adding Shortcodes to WordPress Plugins

Shortcodes are an easy way to execute a function on a page or a post of your WordPress plugin. Adding a shortcode is not a rocket science and it does not require much effort apart from that involved in writing the function for which you are creating the shortcode. Shortcodes can also be used to render dynamic forms on your WordPress website or blog.

You need to just do the following to add a fully functional shortcode on your WordPress blog or website:

  1. Write the function for which you want to create the shortcode.
  2. Add the shortcode using the add_shortcode(‘tagname’, ‘functionname’) method in the shortcodes file.
  3. Give the path(URL) to the shortcodes file in the function.php file of your current WordPress theme.
  4. Insert the tagname for the function in the step 2 in the page or post using [] brackets.

For example, I create the following function that I want to use in my plugin to execute on a page or a post:

function my_function(){

//do something here

}

I create a file my_shortcodes.php, and in that I give the path to the file where the function is located, and use the add_shortcode() method to define the shortcode for the function above. In my shortcodes.php, I will add the following lines:

include ‘path to the file where the function is defined/filename.php’;
add_shortcode(‘myFunction’, ‘my_function’);

The names that you use above for your functions and shortcode tags can be anything till the time they do not conflict with other function and tag names. For example, I can use add_shortcode(‘foo’, ‘my_function’) to define the shortcode, till ‘foo’ is not the tagname of another function for which the shortcode is defined.

Then in the functions.php file of my current theme, I will include the following line:

include ‘URL to the shortcodes file/my_shortcodes.php’ ;

Finally, in the page or post, where I want the function to execute, I will add the following code from the visual or text editor:

[myFunction]

Now, when I open my page or post in the web-browser, the rendered/executed function is available on the page or post.

For more information on adding shortcodes, please visit codex.wordpress.com or look at various tutorials that are available on the Internet.

Hope this post makes sense, and that you liked it.

Leave a Comment

Your email address will not be published. Required fields are marked *