WordPress Code Snippet for PHP Display Shortcodes

I’m always finding myself having to look through my notes for this little snippet for php display shortcodes. I use it often enough to have to look for it, but at the same time, not often enough to commit it to memory. So here, once and for all, is the PHP code to display a shortcode in a WordPress template file.

The PHP Display Shortcodes Snippet

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

Where [shortcode] is the shortcode that you want to display.

While we’re here, what the above code is doing is first identifying itself as a PHP section of code using the opening and closing php tags <?php opens the section of PHP code and ?> closes it, in a similar fashion as opening and closing HTML tags. These two components in the code tell your browser that whatever is contained inside is a segment of PHP.

Then it is calling an echo (printing out) to “do_shortcode”. This means that when you use echo, you’re telling the browser to “display” something in very simple terms. Within the “do_shortcode” function, we’re giving it an argument. That argument is the shortcode itself. We’re sending the value which is whatever shortcode you want to display. This can be a shortcode for a form, gallery or some other plugin shortcode you were provided. Then we close up the PHP section with ?>.

Now I won’t have to dig through my notes for this php display shortcodes snippet anymore. Hooray!

Resources

WordPress Documentation, Do_Shortcode
Describes this little function in immense detail with examples!


Leave a Reply

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