How To Create A Shortcode In WordPress

When you’re feeling like adding some extra features to your website, adding a shortcode is a great way to do it. But how do you create a shortcode for your WordPress site? In this article, we will teach you how to create a shortcode in WordPress

What are shortcodes

Shortcodes are pieces of code that can quickly be added to various areas of your WordPress site, giving you the opportunity to fully customize the functionality available. While shortcodes can be complicated and time-consuming to make, there are many tools available on the internet that make the process much easier. We’ll go over how to do it in this article!

How to create a function

Before we create a shortcode we should create a function. A function is the piece of the code that will be executed when the shortcode is called. In this example, we will create a simple function that will print “Hello World!” to the place where the shortcode is placed. You can change this text and function to be anything you like.

This code should be placed in your functions.php file.

//Function to echo Hello World!
function bloginbox_helloworld() {
    echo "Hello world!";
}

How to create a shortcode

Now that we have the function that actually does something we can create the shortcode that executes the function every time the shortcode is called.

// shortcode to execute the function
add_shortcode('SHORTCODE_NAME_HERE', 'bloginbox_helloworld');

The shortcode is made of two parts. The first part “SHORTCODE_NAME_HERE” is the name we call our shortcode, so when placed on a WordPress page you would call it [SHORTCODE_NAME_HERE].

The second part is the function we want to execute when we call this shortcode. So if you would want to execute some other function than the one we just created, simply add it instead of the ‘bloginbox_helloworld’ to the shortcode.

Conclusion

In conclusion, if you want to create shortcodes to automate simple stuff on your WordPress, simply follow these three steps:

  1. Create the function
  2. Create the shortcode
  3. Add the shortcode to the post or page you want the code to be executed

Here is the full code one more time so you can simple copy and paste it to your functions.php to test it out:

// Function to echo Hello world!
function bloginbox_helloworld() {
    echo "Hello world!";
}
// shortcode to execute the function
add_shortcode('SHORTCODE_NAME_HERE', 'bloginbox_helloworld');

Similar Posts

Leave a Reply

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