Execute Shortcodes in your Theme Files

WordPress code

Shortcodes are very useful for quickly tapping into predefined functionality or appearances, set by either plugins or themes. The trouble is that if you include them in a theme file as raw code, they’ll just appear as plain text and won’t be executed as you might hope or expect. So in order to execute a shortcode in a theme file, to get a particular style for something, or to execute a function, you need to do the following.

Using shortcodes in theme files

When you go to edit the theme file where you want to use the shortcode, all you have to do is insert the shortcode content that you want to execute inside a filter, which will execute the shortcode that you put inside.

For example, say a theme comes with shortcodes for creating columns of one third and two thirds, that you want to hard-code into a particular part of your theme. So your shortcode might look something like this:

Now, if I want to use this within a theme file, I can enclose it within a WordPress function – do_shortcode. So in my case, we want to echo the results of performing a do_shortcode on the content I wrote out above. So the line of code would look like this:

Once you insert that, save it and refresh the page, you should see that the shortcode has been executed and you see the content as you intended it.

2 thoughts on “Execute Shortcodes in your Theme Files”

  1. Richard Coleman says:

    Hi Dave,

    Thanks for the post.

    I have one question, please excuse my lack of knowledge.
    As the Editor no longer appears to be present on WP, in order to add this code do we access a particular file in the back end?

    Many thanks, really enjoying your site.

    Richard C

    1. The editor is still available, assuming you have a self-hosted site and not a wordpress.com site, and your access to it has not been restricted. You can edit it directly from your host’s file manager though instead of through the built-in file editor in WordPress.

Leave a Reply