Skip to content

Instantly share code, notes, and snippets.

@fiko
Created December 3, 2022 01:21
Show Gist options
  • Save fiko/77537cc790586550358769d4be90b5aa to your computer and use it in GitHub Desktop.
Save fiko/77537cc790586550358769d4be90b5aa to your computer and use it in GitHub Desktop.
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