WordPress offers thousands of different plugins that let you add alot of different functions and features to your website. Furthermore most of these can easily be integrated across your website with a few simple short-codes which you simply copy paste into the WordPress editor. However what do you do when you want to integrate that shortcode into your custom template pages? Or maybe you want to add something to your page.php file so that the new feature/function is automatically added to every new page?
This is where the do_shortcode function comes into play. With do_shortcode you can easily use any plugin’s shortcode within your WordPress theme files. So lets say we have a gallery plugin which has a [show_gallery] shortcode. If we want to add this within our page template file we simply use the following syntax:
echo do_shortcode('[show_gallery]');
The same concept applies to the longer shortcodes along with their own variables, as provided by Contact Form 7:
echo do_shortcode('[contact-form-7 id="91" title="quote"]');
You can also take things a step further and store the shortcode inside of a variable. This allows you to then call upon the variable whenever you wish to use the shortcode. So let’s say we are creating a custom page which will display either an Order or a Quote form. We can store the necessary shortcodes for our forms into two different variables, and then make us of the PHP if/else functionality to choose which form to display.
$quoteForm = do_shortcode( '[contact-form-7 id="22" title="quote"]' ); $orderForm = do_shortcode( '[contact-form-7 id="23" title="quote"]' ); if ($formType == "Quote") { echo $quoteForm; } else { echo $orderForm; }