Firstly, never use objectManager like you did in your phtml or in any
block class. You should always use automatic constructor's dependency
injection system.
I suggest you to utilise Magento 2's Service Contract, if you'd like to do it Magento way. There might be lots of methods available ported from Magento 1 but those will be removed in future updates - 'getUsedProducts' is one of them.
Add the following code in your block class:
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Api\LinkManagementInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Registry;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var LinkManagementInterface
*/
protected $linkManagement;
/**
* @var LinkManagementInterface
*/
protected $registry;
/**
* @param LinkManagementInterface $linkManagement
* @param ProductRepositoryInterface $productRepository
* @param SearchCriteriaBuilder $searchCriteriaBuilder
* @param Registry $registry
*/
public function __construct(
LinkManagementInterface $linkManagement,
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
Registry $registry
) {
$this->linkManagement = $linkManagement;
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->registry = $registry;
parent::__construct();
}
public function getChilds()
{
$parentId = $this->registry->registry('current_product')->getId();
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('type_id', 'configurable')
->addFilter('entity_id', $parentId)
->create();
$configurableProducts = $this->productRepository
->getList($searchCriteria);
foreach ($configurableProducts->getItems() as $configurableProduct) {
$childProducts = $this->linkManagement
->getChildren($configurableProduct->getSku());
}
return $childProducts;
}
Now you can get the $childProducts collection in your blocks phtml something like:
$childProducts = $block->getChilds();
foreach ($childProducts as $child) {
$childId = $child->getId();
}
echo $childId();