Using WordPress ‘do_shortcode()’ PHP function

The do_shortcode() WordPress PHP function searches content for shortcodes and filters these shortcodes through their hooks. If no shortcode tags are defined, then the content will be returned without any filtering. This might cause issues when plugins are disabled but the shortcode will still show up in the post or content.

Usage

Here’s a generic example of how to use the function:

// Use shortcode in a PHP file (outside the post editor).
echo do_shortcode('[gallery]');

In this example, the ‘gallery’ shortcode will be executed and its output will be echoed.

Parameters

  • $content (string) – Required. This is the content to search for shortcodes.
  • $ignore_html (bool) – Optional. When set to true, shortcodes inside HTML elements will be skipped. Default: false.

More information

See WordPress Developer Resources: do_shortcode()
This function was implemented in WordPress 2.5.

Examples

Using do_shortcode() with opening and closing shortcode:

$text_to_be_wrapped_in_shortcode = 'This is my text';
echo do_shortcode('[iscorrect]' . $text_to_be_wrapped_in_shortcode . '[/iscorrect]');

This will wrap the text inside the ‘iscorrect’ shortcode and echo its output.

Enabling the use of shortcodes in text widgets:

add_filter('widget_text', 'do_shortcode');

This will enable the use of shortcodes in your text widgets.

Using do_shortcode() in a form like Landing Page Template:

echo do_shortcode('[contact-form-7 id="91" title="quote"]');

This will execute the ‘contact-form-7’ shortcode with the specified id and title, and echo its output.

Storing the shortcode in a variable:

$var = do_shortcode('[gallery]');
echo $var;

This will execute the ‘gallery’ shortcode, store its output in the variable $var, and then echo $var.

Parsing a custom string with shortcodes:

$string = 'This is a [bold]string[/bold] with a shortcode.';
$string = do_shortcode($string);

This will parse any shortcodes in the string and replace them with their corresponding output.

Remember, shortcodes must be enclosed in square brackets ([ ]) to work correctly.