I want to show the product's variation images. However, if there is no variation image, it just shows the parent's image and I wouldn't expect that. At least I would expect an opportunity to check if the image comes directly from the variation or from the parent.

add_action('woocommerce_before_add_to_cart_form', 'test_funktion');
function test_funktion(){
    //Get all variations
    global $product;
    $variationer = $product->get_available_variations();

    //Looping thorugh all
    foreach($variationer as $vari){
        //Get the variation ID
        $varid = $vari['variation_id'];

        //Echoing for testing
        echo '<br>Variation ID: '.$varid.' Image ID: ';

        //Get the image ID from the variation ID
        $variation = new WC_Product_Variation( $varid );
        $image_id = $variation->get_image_id();

        //echoing for testing
        echo $image_id;

Variation ID 1872 has an image uploaded. The rest does not but they return the parents image ID as shown on the test product: http://webintas.dk/wordpresstest/vare/pike-boots-combat-boot/

How can I check if the returned image is from the parent or from the variation itself?



If you check for the image ID with parameter $context = 'edit', you will only get a returned ID if the image is set directly to the variation. The code looks like this:

$image_id = $variation->get_image_id('edit');
    if ($image_id){
        //Only if there is an image to the variation itself
        echo $image_id;

Ref: https://docs.woocommerce.com/wc-apidocs/source-class-WC_Product.html#662-671

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.