Shortcodes in your wordpress theme

Shortcodes is a code reference that is inserted into either templates, pages or posts. When displaying content, wordpress replaces shortcodes with actual code.

A simple example would be a shortcode for inserting an adsense add.

Defining Shortcodes

In your functions.php file, add the following code:

function get_inline_ad($atts) {
    return '<span class="widget-title">Sponsored Link:</span>
	<script async src="//"></script>
	<!-- Unit name from adsense -->
	<ins class="adsbygoogle" 
	    (adsbygoogle = window.adsbygoogle || []).push({});
add_shortcode('sc_adsense_inline', 'get_inline_ad');

A method named get_inline_ad is created that returns the google adsense code. You can go to, create and setup an account and then create a new ad unit – from that you can get the adsense code to insert.

The last line is registering the shortcode ‘sc_adsense_inline’ and telling wordpress to replace it with whatever the method ‘get_inline_ad’ returns.

Using Shortcodes

Edit an existing post or add a new post, then either in the visual view or the text view, try and write [sc_adsense_inline]. It should then look like the ad below (remember to disable adblockers):

After saving, view the post. It should now display an ad in the place where you wrote the shortcode.


Leave a Reply

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