Magento – Magento2 Get parent image from a simple product (configurable)

magento2

How can I get parent image from a simple product if the simple product has no base image?

The following code gets the simple product image in a template file.

$_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
$productImage = $_imagehelper->init($product, 'category_page_list')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(400)->getUrl();

Best Answer

Assuming you want the parent of the simple product you would use the following

$product = $_product->getId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($product);
 if(isset($product[0])){
     //this is parent product id..
     $product[0];
     //here you can load up the parent product and get its image just rememeber to wrap in an if statement to check if child product image is set
}
Related Topic