Daily Code: Day 2 – Show Me…. Bananas!

Daily Code: Day 2 – Show Me…. Bananas!

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:

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:

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:

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:

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]



Join the Conversation

Loading Facebook Comments ...

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × 2 =