Hello Magento Friends,
Today’s blog is about fetching parent product ID from child product ID for bundled and grouped products in Magento 2.
Magento supports 6 Product Types to manage your catalog. In which Grouped Products and Bundled Products contain child products. When you have the requirement to get the parent product ID from the child product ID, here is the solution.
Let’s see How to Get Parent Product ID from Child Product ID for Bundled and Grouped Products in Magento 2.
Contents
Steps to Get Parent Product ID from Child Product ID for Bundled and Grouped Products in Magento 2:
Step 1: Create a file at the below path
app\code\Vendor\Extension\Helper\Data.php
And add the below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php namespace Vendor\Extension\Helper; class Data extends \Magento\Framework\App\Helper\AbstractHelper { protected $bundletype; protected $grouptype; protected $_productFactory; public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Bundle\Model\Product\Type $bundletype, \Magento\GroupedProduct\Model\Product\Type\Grouped $grouptype, \Magento\Catalog\Model\ProductFactory $_productFactory) { $this->bundletype=$bundletype; $this->grouptype=$grouptype; $this->_productFactory = $_productFactory; parent::__construct($context); } public function getBundleParentProduct($id) { $bundleproduct = $this->bundletype->getParentIdsByChild($id); if(isset($bundleproduct[0])) { $product= $this->_productFactory->create()->load($bundleproduct[0]); return $product; } else { return false; } } public function getGroupParentProduct($id) { $groupproduct = $this->grouptype->getParentIdsByChild($id); if(isset($groupproduct[0])) { $product= $this->_productFactory->create()->load($groupproduct[0]); return $product; } else { return false; } } } |
Step 2: Call function from the template file
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $helper = $this->helper('Vendor\Extension\Helper\Data'); $ childproductid=33; $parent_bundle = $helper->getBundleParentProduct($childproductid); echo “Product Id : ”.$parent_bundle ->getId(); //get id of bundle parent product echo “Product Name : ”.$parent_bundle ->getName(); //get name of bundle parent product $parent_group = $helper->getGroupParentProduct($childproductid); echo “Product Id : ”.$parent_ group ->getId(); //get id of group parent product echo “Product Name : ”.$parent_ group ->getName(); //get name of group parent product ?> |
Conclusion:
This way you can obtain Parent Product ID using Child Product ID for Bundled and Grouped Products with the help of the above solution. In case you are unable to get the output, connect with me through comments.
Happy Coding!