Create a WordPress Shortcode

Home / Guides / Converting Shortcodes to Blocks in WordPress / Create a WordPress Shortcode
Lesson 4 of 7
3m read.

We will create a WordPress shortcode for our scbdemo plugin in this tutorial.

Watch: How to create a WordPress shortcode.

Create WordPress Shortcode Process.

  • Navigate to the Shortcodes folder.
  • Create a file – Scbdemo.php. This will be the class file for our shortcodes.

Shortcode Class – Scbdemo.php

Below is the code we will add to the Scbdemo.php file.

Code explanation.

Line 8

  • This line defines our namespace. We are inside the core/Shortcodes folder. You should recall that we mapped the core folder to our MRK_Scbdemo namespace.
  • The namespace for this file becomes. MRK_Scbdemo\Shortcodes which maps to .core/Shortcodes.

Line 10: We import the BaseController class. We may use it to access some base methods.

Line 15-37

On line 15: Defines the Scbdemo class. This class extends the BaseController class.

Line 22-24: This is the register method that will register our add_shortcode hook. This hook adds our [mrk_scbdemo] shortcode and its call-back function mrk_scbdemo_shortcode.

Line 31 – 36: The mrk_scbdemo_shortcode method. Call-back function for our [mrk_scbdemo] shortcode. It returns a string of HTML that we set on line 33.

Register Shortcode class in Init.php

Go to the Init.php file and add the Scbdemo shortcode class in the get_services array, as seen on line 23.

Register the Scbdemo shortcode Class in the Init file.
Register the Scbdemo shortcode Class in the Init file.

Code Workflow

When the Init class runs, it accesses the Scbdemo shortcode class using the get_services method. The class is instantiated, and its instance is stored as a service.

Inside this service (Scbdemo class instance), it calls the register method.

This method registers the add_shortcode hook. When the hook is fired, the [mrk_scbdemo] shortcode calls the mrk_scbdemo_shortcode function.

The mrk_scbdemo_shortcode function returns the string of HTML, which is the shortcode’s output on the site.

Test for Shortcode

  • Go to the demo page.
  • Add the [mrk_scbdemo] shortcode to the page.
  • Publish or update to save the changes.
Testing the mrk_scbdemo shortcode on the site.
Test the mrk_scbdemo shortcode on the site.

Guide recap

In this guide, we have looked at the following;

  • How to create WordPress Block.
  • The shortcode code class – scbdemo.php.
  • How to register our shortcode class in Init.php.
  • Workflow within our Shortcode
  • Testing the shortcode.