-2

I'm designing template from scratch in WordPress, I am having a problem on getting product images/Gallery on single.php by product ID; here's my code:

function GetImageUrlsByProductId( $productId){

    $product = new WC_product($productId);
    $attachmentIds = $product->get_gallery_image_ids();
    $imgUrls = array();
    foreach( $attachmentIds as $attachmentId )
    {
        $imgUrls[] = wp_get_attachment_url( $attachmentId );
    }

    return $imgUrls;
}
$id = the_ID();
echo $id."<br/>";
$title = get_the_title();
echo $title."<br/>";
print_r(GetImageUrlsByProductId($id));

It showed empty array, but I want images path.

Maxime
  • 8,645
  • 5
  • 50
  • 53
Roxas Zohbi
  • 599
  • 4
  • 13
  • 20
  • If you are looking fror woocommerce product ID I don't believe you want the_ID(); https://stackoverflow.com/questions/27385920/woocommerce-get-current-product-id – Second2None Jan 04 '19 at 06:06
  • I am not looking for product id, I want a product gallery on my single.php in the easiest way whether it gets by product id or some function to call – Roxas Zohbi Jan 04 '19 at 06:08
  • @RoxasZohbi you are using the_ID() function but this function is only use to show id of post that means according your scenario you have to use this get_the_ID() to get id of post and then it can be store in $id variable .You can check my answer below – Bhavin Thummar Jan 04 '19 at 06:57
  • For more information you can check this link https://developer.wordpress.org/reference/functions/the_id/ and this one https://developer.wordpress.org/reference/functions/get_the_id/ – Bhavin Thummar Jan 04 '19 at 06:58
  • Above both link,you can identify the difference of display and retrieve the data. – Bhavin Thummar Jan 04 '19 at 07:00

1 Answers1

0

I think this code can solve issue.

<?php
    $product_id = get_the_ID();
    $product = new WC_product($product_id);
    $attachment_ids = $product->get_gallery_attachment_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');

        }
?>
Bhavin Thummar
  • 1,255
  • 1
  • 12
  • 29