How to Use WordPress Shortcodes in a Template in PHP

Have you ever wondered how to use a WordPress shortcode within a template of your theme/template in WordPress? There are several uses cases where it’s very valid to use a shortcode in a template. Traditionally, though, shortcodes are used within the editor’s content region or within some widgets that get displayed on various modules of the site.

Before we go onto describing how to set this up, you might be wondering what shortcodes are in WordPress. You can skip this section if you are already familiar with shortcodes in WordPress, if you are new then keep reading.

Shortcodes in WordPress are essentially bits of text you can use in the content area to invoke some kind of function to accomplish certain tasks. A typical example is maybe you want to display an Instagram, Youtube, Facebook or even a Twitter embed, you can easily use the shortcode that WordPress provides to show an embed without having to write the full code for the embed. In a nutshell, they provide a very convenient way of displaying slightly more complex modules on the page.

The default out-of-the-box WordPress comes with a lot of shortcodes, you can view a list of all the shortcode in the documentation here. Guess what? WordPress allows you to write your own shortcodes, and there are numerous plugins that offer their functionality via shortcodes as well.

To use a shortcode, be it a built-in shortcode or one that is provided by a plugin or even something that you wrote, you can use a function that WordPress provides called do_shortcode. Using this function you can easily execute the logic required for the shortcode to run and display the results in the template.

<?php echo do_shortcode("[shortcode]"); ?>

Just as displayed above, you replace the word “shortcode” with the actual name of the shortcode. As such, if you want to use the twitter timeline shortcode, you just have to replace it with the twitter timeline shortcode with the required attributes like below.

<?php echo do_shortcode("[twitter-timeline username=yourhandle]"); ?>

Try this little trick in your code next time and let know how you like it. We hope this post is helpful, feel free to leave any comments and questions in the comment boxes below and feel free to reach us on Twitter or Facebook. Also, remember to signup for our newsletter to receive periodic updates of our server.

How to Use WordPress Shortcodes in a Template in PHP
5 (85%) 485 votes

Join over 20,000 users and get our best content

Each week we send 1 email to 20,000 smart entrepreneurs just like you. Enter your email below to join the crew.

Thank you for subscribing.

Something went wrong.