title: WooCommerce dynamic thumbnail images for variable products
body: <p>I am trying to create a function that sets the thumbnail for variable products. At the moment I would have to go into the backend and apply the image manually but I want something more dynamic. </p>
  
  <p>For example lets say I have a variable product called Lamp inside there are three child products. Each child product is the same but vary in colour (blue, green, yellow). Now what I want is the variable product to have same image as the first variation inside but if a colour filter of yellow is applied to the shop page I want to get the image for that variation and display that instead for the variable thumbnail. </p>
  
  <p>I have almost created this functionality but there is an issue both if statement can be true for different products and I end up with multiple thumbnails for the product.</p>
  
  <p>How can I improve this function? </p>
  
  <pre><code>remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
  add_action( 'woocommerce_before_shop_loop_item_title', 'set_product_image', 10);
  
  function set_product_image() {
      global $product;
  
      if( $product-&gt;is_type('variable') ){
          foreach ( $product-&gt;get_visible_children() as $variation_id ){
              $variation = wc_get_product( $variation_id );
  
              $product_colour = strtolower( $variation-&gt;get_attribute('colour') );
  
              $filter_colour = $_GET['filter_colour'];
  
              if( $product_colour == $filter_colour){
                  echo $variation-&gt;get_image( array(300, 300) );
  
              }else if( $product_colour != $filter_colour ){
                  // echo $variation-&gt;get_image( array(300, 300) );
  
              }
          }
      }else if( $product-&gt;is_type('simple') ){
          if ( has_post_thumbnail() ) {
              echo $product-&gt;get_image( array(300, 300) );
          }
      }
  }
  </code></pre>