1

How can I get the first product image of a product, If none of the products images are set as base, small or thumbnail image?

In all the examples I found based on getting base, small or thumbnail images for a product.

Thanks!

1 Answer 1

2
public function __construct(
    \Magento\Catalog\Model\Product $product
){
    $this->product = $product;
}

public function getImageByProductId($id){
    $product = $this->product->load((int)$id);
    $small_img = $product->getData('small_image');
    $thumbnail = $product->getData('thumbnail');
    $image = $product->getData('image');


    if ((empty($small_img) || $small_img == "no_selection") ||
        (empty($thumbnail) || $thumbnail == "no_selection") ||
        (empty($image) || $image == "no_selection")) {

        $firstImageObject = '';
        $images = $product->getMediaGalleryImages('images');
        if (!empty($images)) {
            $img = 0;
            foreach ($images as $imagkey => $imgvalue) {
                if ($img === 0) {
                    $firstImageObject = $imgvalue;
                    $img++;
                }
            }
            print_r($firstImageObject->getData());
        } else {
            echo 'no images found';
        }
    }
}

try this one.

3
  • Which file do I need to edit with this code?
    – Crim
    Commented Aug 4, 2021 at 10:51
  • this is standalone function. Its up to case by case, where you would like to use.
    – sandip
    Commented Aug 4, 2021 at 11:12
  • @sandip Can you let it loop through all products which return no_selection for image?
    – JorgB
    Commented Apr 17 at 12:17

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.