Is there a hook in WordPress that I can use to filter the output of a specific shortcode? Something like this:
add_filter('shortcode_output', 'my_filter_function', 2);
function my_filter_function ( $output, $shortcode ) {
....
}
Where $shortcode
would be something like [my_schortcode]
or even better, shortcode and its attributes separated into an array.
There is no filter that I know of that is meant to target individual shortcodes like you want.
You can filter attributes with
shortcode_atts_{$shortcode}
though.You can hijack another shortcode by creating your own callback and registering it with the original shortcode slug. I think that is what you are probably going to need to do.
Proof of concept:
Now try to use a gallery 🙂
WordPress 4.7 introduced a new filter,
do_shortcode_tag
, to do exactly this.While there is no hook, there is a small workaround that makes your end-goal possible. You can create a new shortcode that, on a per-instance basis, you always wrap around any other shortcode whose output you want to filter.
Usage in a post, etc:
In functions.php:
The only thing that you can filter is the attributes fo the shortcode:
Point is, that
$shortcode
is the third argument when registering a shortcode. This argument is pretty new and nearly no shortcode uses it, therefore it will fall back to the default – which is astring
of''
.This leads to a funny result:
So, yes, with a 90% chance we need to filter the output of every(!) shortcode and try to somehow identify the shortcode by either some default arguments (
$pairs
) or by input arguments (impossible). Then, finally we’re able to process the output. Are we able to process the string itself? No. This has to be done the way @s_ha_dum showed above.While @s_ha_dum gave a decent answer, you can create a new shortcode for the purpose of filtering an existing shortcode. For example,
note that for the
[embed]
shortcode, you have to useinstead of
do_shortcode