I have read the WordPress Codex on add_filter and apply_filter countless times, but it wasn’t until reading woocommerce source code today that something clicked in the way that maybe I don’t understand the way apply_filter works or maybe I don’t quite understand how it creates a new hook and when/where is the function defined for the new hook?
Review the wordpress codex again
CODEX: apply_filters( string $tag, mixed $value ) Call the functions
added to a filter hook.The callback functions attached to filter hook $tag are invoked by
calling this function. This function can be used to create a new
filter hook by simply calling this function with the name of the new
hook specified using the $tag parameter.The function allows for additional arguments to be added and passed to
hooks.// Our filter callback function
function example_callback( $string,
> $arg1, $arg2 ) {
> // (maybe) modify $string
> return $string; } add_filter( 'example_filter', 'example_callback', 10, 3 );
/* Apply the filters by calling the ‘example_callback’ function we
“hooked” to ‘example_filter’ using the add_filter() function above.
-> ‘example_filter’ is the filter hook $tag.
-> ‘filter me’ is the value being filtered.
-> $arg1 and $arg2 are the additional arguments passed to the callback.
$value = apply_filters( 'example_filter', 'filter me', $arg1, $arg2 );
You can see they show one way to use apply_filters: that is in combination with add_filters where the function is defined and linked to the $tag.
The use is intuitive. You define it, you use it.
So what about the other scenario, creating a new filter hook on the fly … If some of you are still saying what? lets reread that part of the codex one more time.
This function can be used to create a new filter hook by simply
calling this function with the name of the new hook specified using
the $tag parameter.
So add_filter isn’t used in this circumstance. Which leads to my question ‘what are we trying to accomplish here? Why are we creating a filter hook here? How do we associate a function with a filter hook that gets created on-the-fly?
The apply_filter codex doesn’t give us an example of how or why we would want to do this which is an oversight, but I keep finding instances of these filter hooks as I was walk my way through woocommerce source over at github.
In woocommerce, for example, I see apply_filter used as follows:
function woocommerce_get_product_thumbnail( $size="woocommerce_thumbnail", $deprecated1 = 0, $deprecated2 = 0 ) {
global $product;
$image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );
return $product ? $product->get_image( $image_size ) : '';
}
I’ve searched for the tag ‘
single_product_archive_thumbnail_size
‘ in woocommerce repository on github. There is only the single occurrence of it as you see here. So how do we use it?