Create WordPress Shortcode
Follow this simple tutorial to create custom WordPress shortcode.
Case Study
I wanted to add short information at the end of my post which belongs to, for example, Category A. The project I am working on has many categories but there were only 15 to 20 posts under Category A and will not increase in the future. Basically, there were two ways I could think of at the moment that can make this happen.
- I could create a post template based on category the post is filed in.
- I could create a WordPress shortcode and add the shortcode at the end of each specific post filed under Category A.
Since there were only 15 to 20 posts that I am working on, I decided to go to with option 2. I created a shortcode function in functions.php and added the shortcode at the end of all my posts in Category A.
WordPress Shortcodes – What is it?
Shortcode Definition from WordPress.org
Since Version 2.5 WordPress support so called Shortcodes. They have been introduced for creating macros to be use in a posts content. For examples of shortcodes and how to use them, see WordPress.com Shortcodes, though some shortcodes featured are exclusive to WordPress.com.
To learn more about Shortcode Api, visit WordPress Shortcode API.
Create WordPress Shortcode
Let’s begin by creating a simple WordPress shortcode. Open your functions.php file and insert the following PHP codes.
Here’s a simple “Hello World!” example.
function hello_world() { return 'Hello World!'; } add_shortcode('hello', 'hello_world');
Enter [hello] somewhere in your page or post. You should see the word “Hello World” in your page once published.
In my case, I needed to pass on a parameter. Now let’s look at parameterized shortcodes.
Open your functions.php and add the following PHP code.
/** Shortcode Callback **/ function sc_weapon($params, $content = null) { $output = '<h2>More information about ' . $content . '</h2> ' . $content . ' is one of the weapons used by so on so on'; return $output; } add_shortcode('weapon', 'sc_weapon');
Save your functions.php file and test the code by entering [weapon]halberd[/weapon] at the end of your post.
You should now see “.. halberd is of the weapons used by so on so on'” at the end of your post.
Try changing the keyword between [weapon][/weapon] to see different results.
How did I apply WordPress shortcode to my projects
I edited all the posts under Category A and added the shortcode at the bottom of each post. I changed the keyword inside [weapon] [/weapon] shortcode depending on the post topic.
Have you used shortcodes in your WordPress projects?