How to get parent product id in magento 2?
For getting the parent product id in your phtml file, you can call code directly by:
$productId = 52; //this is child product id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
if(isset($product[0])){
//this is parent product id..
echo $product[0];
}
You can call it's in block file, Magento specific way by,
protected $_catalogProductTypeConfigurable;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
//for getting parent id of simple
\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $catalogProductTypeConfigurable,
array $data = []
) {
//for getting parent id of simple
$this->_catalogProductTypeConfigurable = $catalogProductTypeConfigurable;
parent::__construct($context, $data);
}
public function getProductData($id) {
$parentByChild = $this->_catalogProductTypeConfigurable->getParentIdsByChild($id);
if (isset($parentByChild[0])) {
//set id as parent product id...
$id = $parentByChild[0];
}
return $id;
}