The do_shortcodes_in_html_tags() WordPress PHP function is used to search and process shortcodes only within HTML elements. It helps to prevent interference with shortcodes that are outside the elements by encoding any [ or ] characters remaining inside elements. This function assumes that the content has already been processed by KSES. Note that users with unfiltered_html capability may get unexpected output if angle braces are nested in tags.
Usage
Here’s a generic example of how you might use the do_shortcodes_in_html_tags() function:
$content = 'This is my content with a [shortcode]'; $ignore_html = true; $tagnames = array('shortcode'); $result = do_shortcodes_in_html_tags($content, $ignore_html, $tagnames);
Parameters
- $content (string): This is the content where you’ll search for shortcodes.
- $ignore_html (bool): When set to true, all square brackets inside HTML elements will be encoded.
- $tagnames (array): This is the list of shortcodes to find.
More information
See WordPress Developer Resources: do_shortcodes_in_html_tags()
Examples
Basic usage
$content = 'This is a post with a [gallery]'; $ignore_html = true; $tagnames = array('gallery'); $processed_content = do_shortcodes_in_html_tags($content, $ignore_html, $tagnames);
This example looks for the ‘gallery’ shortcode in $content and processes it.
Multiple shortcodes
$content = 'This is a post with a [gallery] and [video]'; $ignore_html = true; $tagnames = array('gallery', 'video'); $processed_content = do_shortcodes_in_html_tags($content, $ignore_html, $tagnames);
In this example, the function will look for and process both ‘gallery’ and ‘video’ shortcodes in $content.
Ignoring HTML
$content = 'This is a post with a [gallery] and [video]'; $ignore_html = false; // change this to ignore HTML $tagnames = array('gallery', 'video'); $processed_content = do_shortcodes_in_html_tags($content, $ignore_html, $tagnames);
This time, the function will ignore HTML elements and not encode square brackets inside them.
No shortcodes
$content = 'This is a post with no shortcodes'; $ignore_html = true; $tagnames = array(); $processed_content = do_shortcodes_in_html_tags($content, $ignore_html, $tagnames);
With an empty $tagnames array, the function will return the original content as there are no shortcodes to find.
Non-existing shortcode
$content = 'This is a post with a [gallery]'; $ignore_html = true; $tagnames = array('non_existing_shortcode'); $processed_content = do_shortcodes_in_html_tags($content, $ignore_html, $tagnames);
In this case, the function will not find the ‘non_existing_shortcode’ in $content and will therefore return the original content.