Using WordPress ‘apply_shortcodes()’ PHP function

The apply_shortcodes() WordPress PHP function searches content for shortcodes and filters shortcodes through their hooks. It is an alias for do_shortcode().

Usage

Here’s a simple use of apply_shortcodes() function:

echo apply_shortcodes('[myshrtcode]Hello World![/myshrtcode]');

In this example, ‘Hello World!’ would be the output, assuming ‘myshrtcode’ has been properly defined.

Parameters

  • $content (string): This is the content in which to search for shortcodes.
  • $ignore_html (bool): Optional. If true, the function will skip shortcodes inside HTML elements. Default is false.

More information

See WordPress Developer Resources: apply_shortcodes()
This function was introduced in WordPress 5.4 and is an alternative to do_shortcode().

Examples

Basic Usage

Using apply_shortcodes() to parse a shortcode within a string.

// Assuming 'myshrtcode' is a registered shortcode that wraps text in a <p> tag.
echo apply_shortcodes('[myshrtcode]Hello World![/myshrtcode]');
// Output: <p>Hello World!</p>

Ignoring HTML

Using apply_shortcodes() with the $ignore_html parameter set to true. This will ignore shortcodes within HTML tags.

// 'myshrtcode' adds a <p> tag around the content.
echo apply_shortcodes('<div>[myshrtcode]Hello World![/myshrtcode]</div>', true);
// Output: <div>[myshrtcode]Hello World![/myshrtcode]</div>

Using a Shortcode with Attributes

Using apply_shortcodes() to parse a shortcode with attributes.

// Assuming 'myshrtcode' is a registered shortcode that wraps text in a <p> tag with a class.
echo apply_shortcodes('[myshrtcode class="highlight"]Hello World![/myshrtcode]');
// Output: <p class="highlight">Hello World!</p>

Combining Shortcodes

Using apply_shortcodes() to parse multiple shortcodes in a single string.

// 'myshrtcode' wraps text in a <p> tag, 'anothershrtcode' wraps text in a <strong> tag.
echo apply_shortcodes('[myshrtcode][anothershrtcode]Hello World![/anothershrtcode][/myshrtcode]');
// Output: <p><strong>Hello World!</strong></p>

Shortcodes in Variables

Using apply_shortcodes() with a variable that contains a shortcode.

// 'myshrtcode' wraps text in a <p> tag.
$text = "[myshrtcode]Hello World![/myshrtcode]";
echo apply_shortcodes($text);
// Output: <p>Hello World!</p>