Sergio R Sergi
Sergio R Sergi

Reputation: 163

Woocommerce get image galleries by product id

How to show images from the product gallery programmatically? I see the option to show featured images; but not to show all images for a product id.

Is it possible to do this?

I try this but couldn't get the images from the product gallery by id in Woocommerce.

<?php

 $gallery = get_post_gallery_images(724);


    $image_list = '<ul id="cfImageGallery">';                       
    foreach( $gallery as $image ) {// Loop through each image in each gallery
        $image_list .= '<li><img src=" ' . str_replace('-150x150','',$image) . ' " /></li>';
    }
    $image_list .= '</ul>';                     
    echo $image_list;  

?>

Upvotes: 12

Views: 39492

Answers (4)

Ajay Ghaghretiya
Ajay Ghaghretiya

Reputation: 822

Use the get_gallery_image_ids() for get the Gallery Attachment Ids because get_gallery_attachment_ids() deprecated since WooCommerce 3.0.0

Upvotes: 3

Dezefy
Dezefy

Reputation: 2096

I have already tested this and it works

<?php
    $product_id = '14';
    $product = new WC_product($product_id);
    $attachment_ids = $product->get_gallery_image_ids();

    foreach( $attachment_ids as $attachment_id ) 
        {
          // Display the image URL
          echo $Original_image_url = wp_get_attachment_url( $attachment_id );

          // Display Image instead of URL
          echo wp_get_attachment_image($attachment_id, 'full');

        }
?>

Upvotes: 37

Thiện Trần
Thiện Trần

Reputation: 1

<div class="row">
<?php

    $attachment_ids = $product->get_gallery_attachment_ids();

    foreach( $attachment_ids as $attachment_id ) {
        $image_link =wp_get_attachment_url( $attachment_id );
        //Get image show by tag <img> 
        echo '<img class="thumb" src="' . $image_link . '">';
    }
?>
</div>

//Get all image by tag <img>

Upvotes: -1

ssaltman
ssaltman

Reputation: 3713

Just to clarify, the above answers will get all but the thumbnail (main) image.

To prepend the thumbnail, use this:

$product_id = '652';
$product = new WC_product($product_id);
$attachment_ids = $product->get_gallery_image_ids();

//This adds the thumbnail id as the first element of the array

array_unshift($attachment_ids, get_post_thumbnail_id($product_id));

print_r($attachment_ids);

Upvotes: 4

Related Questions