You’re probably used to seeing shortcodes in WordPress. Shortcodes normally look like [shortcode] or [shortcode option=”option” setting=”setting”]. Plugins and Themes add shortcodes to extend the functionality of WordPress. WordPress sees the square brackets and replaces what we see in the editor with some other content. Whether the shortcode is replaced with one line of text, or a very large and complex block of code depends on what WordPress is instructed to do.
You can tell WordPress what to do with a Shortcode
It’s very simple to create your own shortcode in WordPress.
The programming is very easy and the possibilities are endless.
Anatomy of a WordPress Shortcode
- You need to create a function which runs anytime your shortcode is used.
- You need to tie that function to a specific shortcode so WordPress knows to replace it. Otherwise, like my example above [shortcode], WordPress won’t do anything with the shortcode and you’ll see the square brackets and text appear on the page or post.
Functions.php or WordPress Plugin?
Shortcode code is normally placed in a theme’s functions.php file. If you have a lot of shortcodes, a better idea is to create a separate file and include it in the function.php file for code cleanliness and easy maintenance.
However, if you ever change themes your shortcodes will all stop working. A better idea is to create a plugin so your shortcodes continue to work no matter what theme is active on your WordPress site. I will show you how to do this later. Leave a comment and I’ll email you when I post the plugin tutorial.
For simplicity and speed, just include the below code in your functions.php file.
Your First WordPress Shortcode
Tell WordPress the Shortcode Exists
We have to tell WordPress to look for, and replace, our new shortcode. In either your functions.php, your included file in functions.php or in your custom plugin, use the add_shortcode() function.
The add_shortcode() function has two arguments:
- The name we want the shortcode to have. What we type between the square brackets. Ex: helloworld.
- The function we want WordPress to run when replacing our shortcode. ex: hello_world()
That’s it! That’s all it takes for the simplest shortcodes!
Adding Shortcode Arguments
Adding some complexity and customization to our shortcodes requires a little code, but it’s still very simple.
WordPress will automatically read the width and height attributes, but we will also set default values so the arguments are optional.
Create the Callback Function
Finally, Register the Shortcode with WordPress
You’re done. Now you can either use the shortcode with no arguments as [randompicture] which will give you a random image 400 pixels by 200 pixels.
Or you can add any width or height you want and get an image which matches that size.
Now you can create custom shortcodes for anything you want on your WordPress website!
Feel free to leave a comment!