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.

About Staff is a design blog about WordPress and web design. We usually write about wordpress, plugins, themes, web design resources, php, css, jquery, adsense and more.. If you want to get notified about our posts, be sure to subscribe to our feed or follow us on facebook. You can also subscribe to our mailing list. No spam, we promise.

3 Comments on HowTo: Use shortcodes in your theme files

  1. Thanks a lot!!

  2. 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 ?

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

Leave a comment

Your email address will not be published.