WordPress do_shortcode is a function in the core WordPress that allows searching the content for shortcodes and filter them through their hooks. In this WordPress shortcode tutorial, I will show you some WordPress do_shortcode examples so you can learn how to use a shortcode in a WordPress page or template file. You will also learn how to use do_shortcode with variables and be able to fix any issue where WordPress do_shortcode is not working.
WordPress shortcode and WordPress do_shortcode
The core WordPress comes with a Shortcode API that allows other plugins/themes to execute a set of functions in posts and pages. WordPress itself uses shortcodes for some core functions as well like embedding a video/audio, creating an image/photo gallery etc. The main purpose of the Shortcode API is to create shortcodes with various attributes like this:
[my_gallery id="163" size="small"]
Each shortcode has a handler function (Usually the plugin/theme who registered it). WordPress automatically filters the shortcode and passes these parameters to the handler function. The handler function can then use these to render special kinds of content (e.g. forms, buttons). Unfortunately, this only works when you use the shortcode in the content area (a filter can be added for widget/excerpt as well). But what happens when you need to use the shortcode in a template file or your theme’s PHP file?
This is when the do_shrortcode function comes in handy. do_shortcode is a way of telling WordPress that you want it to filter the shortcode even though it’s not present in the content area. As long as it’s embedded in a PHP file (since do_shortcode is a PHP function created by WordPress) WordPress should be able to filter the shortcode.
In order to filter a particular shortcode via the do_shortcode function, you just need to pass the shortcode as a function parameter. For example:
echo do_shortcode('[my_gallery id="163" size="small"]');
Here, echo will print the content returned by the handler function of the shortcode.
Ignoring HTML in WordPress do_shortcode
The example above shows the default behavior of the WordPress do_shortcode function. But you can add a second parameter to customize it. This parameter is optional and set to false by default. This allows you to skip filtering of a shortcode inside HTML elements. For example:
echo do_shortcode('[my_gallery id="163" size="small"]', true);
That’s all you need to know about the WordPress do_shortcode function. If you have any questions feel free to share it in the comments.