The post shows the programmatic method to get parent product ID in Magento 2. Magento 2 has 3 product types named configurable, bundled and grouped, those have children products. You might be wondering if you can get parent product ID of these 3 product types.
You can use the solution if you are selling the store products on 3rd party platforms like Facebook shop and care to enhance the shopping journey.
For example, I used the below method for a client who wanted to redirect the customers to the website directly on the cart page from the Facebook shop product. And the product had to be already added to the cart. The customer can skip the step to manually add the product to the cart in the Magento 2 store. However, to implement it, I needed to get the parent product ID as the simple product configuration can’t be displayed.
Hence, the solution:
Method to Get Parent Product ID in Magento 2:
namespace [Vendor]\[Module]\Helper; use Magento\Framework\App\Helper\Context; class Data extends AbstractHelper { protected $configurable; protected $grouped; public function __construct( Context $context, \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurable, Magento\GroupedProduct\Model\Product\Type\Grouped $grouped ) { $this->configurable = $configurable; $this->grouped = $grouped; parent::__construct($context); } public getParentId($childId){ /* for simple product of configurable product */ product = $this->configurable->getParentIdsByChild($childId); if(isset($product[0])){ return $product[0]; } /* for simple product of Group product */ $parentIds = $this->grouped->getParentIdsByChild($childId); /* or for Group/Bundle Product */ $product->getTypeInstance()->getParentIdsByChild($childId); } }
That’s it. You need to get current product ID in Magento 2 while applying product-related customizations.
Feel free to share the post with fellow developers on social media.
Thank you.