Search code examples
phpwordpresswoocommercegallerysrc

Get the URL of the first image from the product gallery in Woocommerce


How can I get the URL of the first image that is uploaded to the product gallery?

I am not talking about the featured image.

I would appreciate any suggestions.


Solution

  • The following will give you the first image Url from the product gallery:

    global $post, $product;
    
    if( is_a($product, 'WC_Product'))
        $product = wc_get_product($post->ID);
    
        $product = wc_get_product(40);
    
    // Get the array of the gallery attachement IDs
    $attachment_ids = $product->get_gallery_image_ids();
    
    if( sizeof($attachment_ids) > 0 ){
        $first_attachment_id = reset($attachment_ids);
        $link = wp_get_attachment_image_src( $first_attachment_id, 'full' )[0];
    
        // Output
        echo $link;
    }