I’m trying to push some variables to google analytics and would like to be able to detect if a shortcode has been included on a page at all.
Anybody know a smart way going about this?
Thank you!
Noel
I’m trying to push some variables to google analytics and would like to be able to detect if a shortcode has been included on a page at all.
Anybody know a smart way going about this?
Thank you!
Noel
You must be logged in to post a comment.
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 functionused here to apply the shortcode:
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?
For anyone who came to this question here is the correct answer:
Use has_shorcode() to detect if a specific shortcode was called. Can be viewed here:
https://developer.wordpress.org/reference/functions/has_shortcode/
So here’s my trainwreck version of it (as it stands this minute, Anmari has given plenty of good ideas). It’s not really flexible at all for anyone else’s use either, but our hosted platform and how people use it is very flexible (makes my life easier):
A simple way, use
$tag
variable within your shortcode function. Get this idea from here