How to Create your own Custom Shortcode in WordPress
Sometimes, no matter how cool your theme or how incredible the visual editing plugin you are using is, there is a feature you want that they just don’t have. And the easiest way to add some really cool functionality into your site is with a shortcode.
Today we’re going to walk you through an easy way to add shortcodes to your site. It doesn’t involve editing your theme or functions.php file. Why? Because that just isn’t portable enough. What if you write your shortcode and it’s amazing, and you want to use it on other sites? Or sell it to make millions of dollars?
The easy way to create portable code for use in WordPress is by creating your very own plugin. So today, you are going to learn how to write your own plugin that lets you create your own custom shortcode in WordPress.
Here’s the code you’ll need:
<?php
/*
* Plugin Name: Your Plugin Name Here
* Description: Tell Us What Your Shortcode Does
* Version: 1.0
* Author: Your Name
* Author URI: Your URL
That was easy, right? Let’s break it down.
That first block that is all commented out is what WordPress uses to display shortcode information.
Obviously, you are going to want to change all of those variables, except maybe starting at version 1.0. Then, there is the shortcode addition itself. This happens in two steps.
Step 1: Create your function
function any_name_here(){
// All your cool code here
}
You’ll want to pick a name for it. If this is going to be a ‘single shortcode’ plugin, maybe you want to name it the same as the plugin file. But, you could add hundreds of shortcodes to one plugin if you wanted, in which case you’d just want to name it intuitively. What you name it really doesn’t matter as it will only be referenced internally by the next bit.
Step 2: Allow the function to be executed
add_shortcode(‘the_shortcode_text’, ‘any_name_here’);
That line says to execute the function we just wrote any_name_here
when we use the shortcode that looks like this [the_shortcode_text]
.
Or, if we go back to the original full plugin code above, if you put [my_shortcode]
into a page like this:
and you then view the page, you’ll see the plugin in action:
And this plugin actually works. To install it, it should be in a folder. Create a folder called my_shortcode
and then save the following code into a file called my_shortcode.php
. Put the folder into a zip archive and upload it to a WordPress site using the default ‘Add a Plugin’ upload feature. Here’s what you’ll see:
Beyond that, your imagination is the limit!
For some inspiration, check out this list of code snippets you can instantly use to get started. And to ensure all your code as performant as possible, make sure you’re using WP Engine host your WordPress sites!