How to detect if a Shortcode is being called on a page?

I have sometimes wondered the same thing – whether wp maybe checked on save and kept a register etc

I had a quick look at the code, and it seems not.

There is however a global $shortcode_tags, and wp has this function

function get_shortcode_regex() {
    global $shortcode_tags;
    $tagnames = array_keys($shortcode_tags);
    $tagregexp = join( '|', array_map('preg_quote', $tagnames) );

    // WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcodes()
    return '(.?)\[('.$tagregexp.')\b(.*?)(?:(\/))?\](?:(.+?)\[\/\2\])?(.?)';
}

used here to apply the shortcode:

$pattern = get_shortcode_regex();
return preg_replace_callback("https://wordpress.stackexchange.com/".$pattern.'/s', 'do_shortcode_tag', $content);

My regex is not that great, but maybe you could do something with that?

Alternatively:

Then there is the brute force way – for each of the shortcode tags, ‘simply’ check if '['.$tag is in the content ?
But then some developers / older plugins do their own funky filters on the content with comments or other custom tags.

So then, you could also check the wp global $wp_filter for $wp_filter['the_content']; the contents should the functions called for “the content”.

To be clever

You could maybe add an action yourself on post save/update, do the check for filters and shortcodes then and store something in a post-meta. Then all you have to do at display time is check the post-meta.

Whew… is it worth it?

Leave a Comment