WordPress codex: apply_filters – clarification on creating a new hook on the fly. How do we use it?

How to use the filter single_product_archive_thumbnail_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?

The author’s of WooCommerce added this filter so that other developers would be able to modify the product’s archive thumbnail size. WooCommerce may not be using this filter itself, but they could.

Here’s how you could use the single_product_archive_thumbnail_size filter. In this hypothetical scenario, we want to override the single_product_archive_thumbnail_size defined by WooCommerce with the image size kruddock_archive_thumbnail defined in the kruddock theme if that theme happens to be active.

/**
 * If the kruddock theme is active, use the kruddock_archive_thumbnail
 * image size for WooCommerce's single_product_archive_thumbnail_size
 *
 * @param string $size name of thumbnail size
 */
add_filter( 'single_product_archive_thumbnail_size', 'single_product_archive_thumbnail_size' );
function wpse_single_product_archive_thumbnail_size( $size ) {
    $theme = wp_get_theme();
    if ( 'kruddock' == $theme->name || 'kruddock' == $theme->parent_theme ) {
        $size="kruddock_archive_thumbnail";
    }


    return $size;
}

Dynamic hooks

A good example of a dynamic hook is the one defined for options, e.g.:

apply_filters( "option_{$option}", mixed $value, string $option )

Let’s say you have a plugin named Kruddock API. In this plugin, you have an option that uses the WP settings API to save a setting named kruddock_api_url.

A developer using your plugin could use the option_kruddock_api_url filter to modify the value returned by get_option( 'kruddock_api_url' ) without actually modifying the stored value of kruddock_api_url (as is the nature with filters; we’re modifying the value on the fly) and without you as the developer of the Kruddock API plugin ever having provided a specific filter for modifying the value of kruddock_api_url.

The WP Settings API allows us to modify any option on the fly using the dynamic filter option_{$option}. Here is how the dynamic hook in this example could be used by another developer:

add_filter( 'option_kruddock_api_url', 'wpse_option_kruddock_api_url' );
function wpse_option_kruddock_api_url( $value ) {
    // Use a different API URL than the default.
    $value="https://subdomain.example.com";

    return $value;
}