How to get the first image gallery of a product in woocommerce in a loop

I want to diplay a product with product image, and when visitor hover that image, will change to first image from product gallery I am using this code to display the image gallery, but displayed all the image from product gallery (I just want 1 image.)

  <?php do_action( 'woocommerce_product_thumbnails' ); ?>

Anybody know how to resolve the problem? Really appreciate for any idea.

Regards

Solutions Collecting From Web of "How to get the first image gallery of a product in woocommerce in a loop"

Along with the product thumbnail (I’m assuming you have this), what you need is a list (array) of the product images – WooCommerce has such methods, eg $product->get_gallery_attachment_ids().

You can grab the first ID in the array and use it to fetch the single image using wp_get_attachment_image(), or wp_get_attachment_url(), etc., then use that as an alternate source for the main (thumbnail) image.

Incidentally, the woocommerce_product_thumbnails call is outputting markup that you probably don’t want to use. You’ll need to either discard this or unhook functions from it to get the output you want.