How to foreach all woocommerce product images?

Member

by jerad , in category: PHP CMS , 3 months ago

How to foreach all woocommerce product images?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 3 months ago

@jerad 

To loop through all WooCommerce product images, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Get the product gallery images
$product = wc_get_product( get_the_ID() );

if ( $product ) {
    $attachment_ids = $product->get_gallery_image_ids();

    foreach ( $attachment_ids as $attachment_id ) {
        $image_url = wp_get_attachment_url( $attachment_id );
        echo '<img src="' . $image_url . '" />';
    }
}


This code snippet fetches the product object using the wc_get_product function, gets the gallery image ids using the get_gallery_image_ids method, and then loops through each attachment id to get the image URL using wp_get_attachment_url. Finally, it prints out the image tag with the image URL.


You can place this code in your WordPress theme or plugin file where you want to display the product images.