HowTo: Use shortcodes in your theme files

Altough shortcodes are made to be used in post content, you can sometimes need it’s functionality in your wordpress theme designs. Here i will show you how to easily use any shortcode in your page templates.

To use a shortcode in our theme templates, we use wordpress shortcode evaluator function do_shortcode. This function takes any text string and it evaluates shortcodes inside the text. Here is how to put a leaderboard ad unit in your page template using shortcodes:

<?php echo do_shortcode('[[adsense type="leaderboard"]]'); ?>

do_shortcode will convert that shortcode to output, and we echo the output.

NOTE : If you forget echo it won’t display anything. This is a common mistake.

You can put the following wrapper function in your functions.php, to make it easier to use later on:

function shortie( $shortcode ){ echo do_shortcode( $shortcode ); /* Name the function as you like */ }

Then in your templates you can use:

<?php shortie('[[adsense type="banner" align="center"]]') ?>

I hope you found this trick userful.

  • Archimidis May 7, 2013

    Thanks a lot!!

  • TechB Apr 8, 2013

    Thanks for the tip. How do you use enclosing shortcodes in php? For e.g. if I want to use this shortcode in a template

    [tabs style=”1″] [tab title=”Tab name”] PHP content [/tab] [/tabs]

    What would be the equivalent php code ?

  • ian Aug 19, 2012

    I can’t believe no one commented on this yet! This helped me out sooooo much. Thanks a ton x a million.

Reply



Free Newsletter

Subscribe to our newsletter for awesome tips about Wordpress and Web Design
* = required field

powered by MailChimp!

Keywords Sponsorship

Powered by WordPress and Shailan