Going Bananas for Day 2 of Daily Code!
Simple WordPress Shortcode
Here is a quick one for today. A custom WordPress shortcode to display an inline image. In this case….. BANANAS!
This is something I wanted to have on KingKode for whenever I wanted to use it. Like right here [bananas].
All lines below are added at the very bottom of functions.php.
Callback Function:
function show_me_bananas() { $image = "<img class='bananas' src='/images/banana-icon.png'/>"; return $image; }
First, we need a function that spits out the image markup. The above sets the img markup as variable $image. Then returns the variable string when fired.
Register Shortcode Function:
function register_new_shortcodes(){ add_shortcode('bananas', 'show_me_bananas'); }
Then, we need to link the previous function to a shortcode. add_shortcode() registers the show_me_bananas() function to the shortcode [bananas]. Note: you can register many other shortcodes with this function.
Hook into WordPress:
add_action( 'init', 'register_new_shortcodes');
Finally, WordPress needs to know that we have a new shortcode. add_action() gets fired when the page is initializing. register_new_shortcodes() is then added to the initialization process and, thus, your shortcodes have been registered.
Oh, yeah… The CSS:
.bananas { display: inline-block; margin: 0px 2px; }
The CSS can be put at the very bottom of stylesheet.css. display: inline-block tells the image to be treated like a block element while inline with the text. margin: 0px 2px adds spacing on either side of the bananas for kerning purposes.
And now we have bananas! [bananas][bananas][bananas][bananas][bananas][bananas][bananas]