Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Magento 2 - Get Parent Product IDs
<?php
namespace Fiko\Catalog\Block;
use Fiko\Catalog\Helper\Data;
class SingleProduct
{
public function __construct(Data $helper)
{
$this->helper = $helper;
}
// How to use it
public function exampleOfHowToUse()
{
$productId = 1;
return $this->helper->getParentIds($productId);
}
}
<?php
namespace Fiko\Catalog\Helper;
use Magento\Catalog\Model\Product\Type as ProductType;
use Magento\Framework\DataObject;
class Data
{
/**
* Constructor
*
* @param ProductType $productType
*/
public function __construct(ProductType $productType)
{
$this->productType = $productType;
}
/**
* Retrieve parent products of a product
*
* @param int $productId
* @return array
*/
public function getParentIds($productId)
{
$parentIds = [];
$productTypes = [];
$productEmulator = new DataObject();
foreach (array_keys($this->productType->getTypes()) as $typeId) {
$productEmulator->setTypeId($typeId);
$productTypes[$typeId] = $this->productType->factory($productEmulator);
}
foreach ($productTypes as $typeInstance) {
$parentIds[] = $typeInstance->getParentIdsByChild($productId);
}
$parentIds = array_merge([], ...$parentIds);
return $parentIds;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment