Assuming you want the parent of the simple product you would use the following
$product = $_product->getId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$configurableProductResource = $objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable');
// Get the parent product IDs for the given child product
$parentIds = $configurableProductResource->getParentIdsByChild($product);
if (isset($parentIds[0])) {
$parentProductId = $parentIds[0];
// Load the parent product
$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
$parentProduct = $productRepository->getById($parentProductId);
// Check if the child product has an image set
if ($_product->getImage() !== 'no_selection') {
// Get the parent product's image
$parentProductImage = $parentProduct->getImage();
// You can now use $parentProductImage as the parent product's image
echo "Parent Product Image: " . $parentProductImage;
}
}
This code does the following:
- Gets the parent product IDs for the given child product using
$configurableProductResource->getParentIdsByChild($product).
- Checks if there is a parent product ID in the $parentIds array.
- If a parent product ID is found, it loads the parent product using the ProductRepositoryInterface.
- It checks if the child product has an image set by comparing it to 'no_selection'
- If the child product has an image set, it retrieves the parent
product's image and stores it in the $parentProductImage variable, which you can use as needed.
Please make sure that you're using the Magento service contracts (like ProductRepositoryInterface) whenever possible instead of directly using the object manager for better code practices and compatibility with future versions of Magento.