How can I create my own shortcode?


If you want to create your own shortcode, we recommend you to do so by creating a child theme first.

Step by step

1. Create child theme
2. Create directory inside your child theme, for example: shortcodes
3. Create a class file (just a simple PHP file) inside shortcodes directory – let’s name it MyCustomShortcode.class.php.
Once done, paste this code:

Most of the above code should be self explanatory, but let’s break it down a bit:

  • getGroupName – function should return name of the group this shortcode belongs to. It can be any name you want – here it will be displayed ad “Custom”
  • getName – friendly name which will appear in Shortcode Generator
  • enqueueScripts – here you can enqueue any javascript files you need. These files will be enqueued at the bottom of your HTML. Scripts will be only added if this shortcode is used on your page.
  • enqueueHeadScripts – here you can enqueue any css/javascript files you need which will be added in head.Scripts and styles will be only added if this shortcode is used on your page.
  • getShortcodeName – name of your shortcode. This name will be used in your code ex. [my_shortcode_name]. Notes about naming your shorcodes can be found here
  • handle – this is the place where you implement your shortcode’s custom logic. It must return HTML which will then be displayed on your pages
  • handle – this is the place where you implement your shortcode’s custom logic. It must return HTML which will then be displayed on your pages. Please note that only parameters which are defined in getAttributes are accessible.
  • getAttributes – define your shortcodes parameters here so that Shortcode Generator can generate a form automatically. Please note that only parameters defined here will be accessible in handle function.

4. Once we have our shortcode ready, we need to register it. Create a file functions.php in root directory.
Once done, copy this content to your functions.php (if file already exists, just paste this code at the bottom):

5. That’s it. Now you should be able to use it: [my_shortcode title=”My Title” url=”http://www.createit.pl” align=”left”]Label[/my_shortcode].

This example can be downloaded here. Please update style.css inside downloaded package PARENT_TEMPLATE_NAME with your main theme name in order to make it work.