How to Get Parent Product ID in Magento 2
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 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:
class Data extends AbstractHelper
public function __construct(
$this->configurable = $configurable;
$this->grouped = $grouped;
/* for simple product of configurable product */
product = $this->configurable->getParentIdsByChild($childId);
/* for simple product of Group product */
$parentIds = $this->grouped->getParentIdsByChild($childId);
/* or for Group/Bundle Product */
Mention your doubts in the Comments section below and I’d be happy to solve them for you.
Feel free to share the post with fellow developers on social media.