4

I want to display a product with a product image and when visitor hovers over that image, it will change to the first image from the product gallery. I am using this code to display the image gallery, but it displays all the images from product gallery. I just want the 1 image.

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

Anybody know how to resolve this problem? Really appreciate any ideas.

Regards

2 Answers 2

3

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.

3
  • My problem is, I dont know how to get the grab first image from gallery. I am using stackoverflow.com/questions/29778288/… but still get all images from gallery.
    – Mailmulah
    Commented Mar 8, 2016 at 12:15
  • 1
    Instead of using foreach in that code, you need to just get the first URL like wp_get_attachment_url( $attachment_ids[0], 'large'). Commented Mar 10, 2016 at 0:46
  • Thank you. With a small modification, the code works fine.
    – Mailmulah
    Commented Mar 10, 2016 at 16:43
1

2018 Update: Need to use get_gallery_image_ids(); instead. Then use wp_get_attachment_url() with the first ID in the array returned.

$product->get_gallery_image_ids();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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