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.

2
  • Which file do I need to edit with this code?
    – Crim
    Aug 4, 2021 at 10:51
  • this is standalone function. Its up to case by case, where you would like to use.
    – sandip
    Aug 4, 2021 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.