How To Create WordPress Shortcodes
WordPress introduced the shortcode API in version 2.5. Shortcodes are now used by a large number of WordPress plugins to allow users to add content to their posts and pages. All of us have probably used them at one time or another. They usually come bundled with plugins, or even themes, and what they do is watch for when you insert something inside square brackets then replace that with some other content; it could be a simple sentence or it could be a massive PHP function, it all depends on what you instructed WordPress to do.
The shortcode API allows you to create your own shortcodes by adding functions to your theme functions.php template (this is located at www.yourwebsite.com/wp-content/themes/yourtheme/).
In addition to creating your own shortcodes, WordPress also includes five default shortcodes with the WordPress core:
audio – Allows you to embed audio files.
caption – Allows you to wrap captions around content. It is commonly used with images.
embed – Allows you to embed a wide range of content such as video, audio and tweets.
gallery – Allows you to insert image galleries.
video – Allows you to embed video files.
In this article we will create some simple WordPress shortcodes to help you create any functionality you like.
A Basic Example
In our first example we want to create a shortcode that will create some “custom text” every time we type [spin2win] into the editor. First we need to create the callback function that will return the “custom text”
function spin2win_func() {
return “I am new shortcode text”;
}
Next we need to add this shortcode to WordPress using the add_shortcode function in either our functions.php file
add_shortcode( ‘spin2win’, ‘spin2win_func’ );
So the full code would be like this :
function spin2win_func() {
return “I am new shortcode text”;
}
add_shortcode( ‘spin2win’, ‘spin2win_func’ );
Note : spin2win_func and spin2win can be any name.
Creating a Shortcode With Attributes
Attributes can expand the functionality of shortcodes by allowing you to pass data through your shortcodes.
When WordPress encounters this we want a function that will insert an image. It needs to read the width and height attributes
function get_images($atts) {
extract(shortcode_atts(array(
‘width’ => 250,
‘height’ => 180,
), $atts));
return ‘‘;
}
add_shortcode(‘getpics’, ‘get_images’);
That’s all 🙂