Search code examples
phpwordpressimagewoocommercehook-woocommerce

Change image by Variation name woocommerce


I'm using the below code for my store single page sidebar, I set image by variation name (type-2).

function image_by_variation() {global $product;if ( ! $product->get_attribute( 'type-2' )) return;echo '<div class="var_img"><img src="image1" height="200" width="500"></div>';}

screenshot - https://prnt.sc/o__rry_OT4g5 Now my type-2 variation has two items,

  1. repaired
  2. never-repaired

I want to change the image banner by variation. Becouse I will select only one variation for one product. some time (repaired) sometimes (never repaired)

Like--> if select repaired (image1), or select never-repaired (image2)


Solution

  • You can do it like this:

    function image_by_variation() {
        global $product;
    
        // Get the type attribute and store in variable.
        $type = $product->get_attribute( 'type-2' );
    
        // Check if type value is empty?
        if ( empty( $type ) ) {
            return;
        }
    
        // Compare with repaired.
        if ( 'repaired' === $type ) {
            echo '<div class="var_img"><img src="https://ksa.revent.store/wp-content/uploads/2022/09/repaired.png" height="200" width="500"></div>';
            return;
        }
    
        // Compare with never repaired.
        if ( 'never-repaired' === $type ) {
            echo '<div class="var_img"><img src="https://ksa.revent.store/wp-content/uploads/2022/09/never-repaired.png" height="200" width="500"></div>';
            return;
        }
    }
    

    Note: if $product->get_attribute( 'type-2' ) return an array then you'll have to change conditions to check repaired Or never-repaired exists in that array or not.