Created
December 3, 2022 01:21
-
-
Save fiko/77537cc790586550358769d4be90b5aa to your computer and use it in GitHub Desktop.
Magento 2 - Get Parent Product IDs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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