WordPress introduced its Shortcode API in 2.5 version, which is a simple set of functions for creating and adding content to your WordPress posts with shortcodes.
Creating shortcodes in WordPress is really easy, and you can create a custom shortcode in few minutes. I’ll show you how to do that
Creating A Simple Shortcode
First, I’ll show you how to create a very basic & simple shortcode. Our simple shortcode will be [mycode] & this code will display an image in the post:
First we need to create a callback function that will return our content:
function mycode_function() { return '<img src="//www.trickspanda.com/wp-content/swift-ai/images/wp-content/uploads/2014/01/Tricks-Panda-png.webp" >'; }
Now, we need to register our shortcode, and the following code will do the work:
add_shortcode('mycode', 'mycode_function');
That was easy! Now, let’s move on to the next level.
Adding Parameters To Shortcode
You can also add some some custom parameters to your shortcode. This time we will define the height and width of our image with following shortcode:
[mycode width=”500″ height=”500″]
Now, this code will add width and height parameters to our shortcode function:
function mycode_function($atts) { extract(shortcode_atts(array( 'width' => 400, 'height' => 200, ), $atts)); return '<img src="//www.trickspanda.com/wp-content/swift-ai/images/wp-content/uploads/2014/01/Tricks-Panda-png.webp" >'; }
Now, just we just need to register the shortcode:
add_shortcode('mycode', 'mycode_function');
That’s it! If you’ll just type the shortcode without defining the width and height, it will use the default 400 by 200 attributes from our function.