Assign Specific Image to WooCoomerce variation

Answer to Stack Overflow question:

The following works for me in my test installation:

/**
 * Replace Woocommerce Product Variation Images
 * based on variation slug 
 */

add_filter( 'woocommerce_product_variation_get_image_id', 'so_filter_wooc_product_variation_images', 10, 2 ) ;

function so_filter_wooc_product_variation_images( $image_id, $data ) {

    //the variation product slug includes "-black"...
    if ( strpos( $data->slug, '-black') ) { 

        //replace with new image by id number
        return $new_image_id ;

    } 

    //else return the image_id according to default settings
    return $image_id ;

}

Now, you don’t have search the product slug as I have done here, necessarily: There are other variables that, depending in part on your installation design, may distinguish one set of variable products from another. By default, however, the product slug for a product variation will combine the attribute terms. So, if your product is “Test Product”; you have two sizes, “Big” and “Small,” and two colors, “Black” and “White”; they’re enabled to produce variations; and the variations are priced (which is required), you’ll get product slugs in the format test-product-big-black and test-product-big-white, and so on, so this seems like a sound method for achieve approximately what you want, focused on the attribute.

It’s not, however, a foolproof method: if the attribute name occurs in the item title, then there’s some chance of occasional overlap – for, say, a product with the title “Test Black Product.” How to solve this issue programmatically is, obviously, a more complicated question: The function I’ve provided here still illustrates the general concept.

As for $new_image_id_number, you could get that in various different ways, so I’ve left that open. For example, you could just find the attachment ID by hovering over the image you want to use in the Media Library. Alternatively, you could create a site option – the old-fashioned away or maybe with Advanced Custom Fields Pro – and extract the ID from an image upload.

Anyway, this working solution turns out to be fairly simple. The filter hook is based on the protected function in abstract-wc-data.php…

$value = apply_filters( $this->get_hook_prefix() . $prop, $value, $this );

…which is constructed from the “hook prefix,” in this case woocommerce_product_variation_, and the property in question, in this case image_id.

(I was initially confused when, viewing the product variation class, I found a filter with a similar structure that essentially duplicates the functionality for certain cases that don’t apply here.)

Leave a Reply