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!
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communitypublic 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.