shortcode

How to create custom WordPress shortcode plugin from scratch

This post has been viewed 197 times.

In this tutorial, we would be creating a custom WordPress shortcode plugin.

What you’ll need:

I assumed that you are already familiar with WordPress plugins. We know that the WordPress plugins are composed of PHP files that can be found in /wp-content/plugins/ directory.

Step 1: Create a folder in the WordPress plugins directory.

I would be creating a folder entitled shortcode-example.

Step 2: Create your plugin file inside the created folder.

In this example we would be creating index.php in /wp-content/plugins/shortcode-example/ as our main plugin file. The content of index.php is as follows:

This will make WordPress recognize the file that we have created as a plugin.

Step 3A: Create a function that contains the content of our shortcode.

Procedural:

Object-oriented:

Step 3B: Create a file that contains the content of our shortcode.

For this example, I created a file content.php. The content of content.php is as follows:

Step 4: Create another function that will render your shortcode content.

Procedural:

Object-oriented:

Step 5: Add a hook for a shortcode tag.

Procedural:

Object-oriented:

The first parameter is the name of our shortcode while the second parameter is the name of the function that has the content. In this example the name of the shortcode is my_custom_shortcode.

Complete Code:

Procedural:

Object-oriented:

Basic usage:

In the WordPress visual editor use the shortcode as [my_custom_shortcode].

This must return Hello! I am a custom shortcode.

That’s it we created a custom WordPress shortcode plugin. To test the plugin you must activate the plugin and it should not return any errors. In case there are any errors, just review the steps to find where it might have gone wrong.

 

Hello, I am a freelance website and mobile application developer. I am also the owner of this website, so if you have any projects for me you can contact me at [email protected] or use the contact page. When I’m not doing some work, I can be found watching Anime/Asian Dramas/American TV Series, playing computer games, and writing tutorials on this website. I run the program repeatedly hoping the error won’t show up next time.