Configurable Product – How to Get Child Product ID in Magento 2

configurable-productmagento2

How to get child product id's from parent product id in magento2 for configurable product?

I want to get child product id of parent product in magento based on parent product id.

Best Answer

Try the below solution:

<?php
    $productId = 5; //Configurable product ID
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $_product = $_objectManager->create('Magento\Catalog\Model\Product')->load($productId);
    $_childProducts = $_product->getTypeInstance()->getUsedProducts($_product);
    foreach ($_childProducts as $simpleProduct){
        echo $simpleProduct->getId();
    }
?>

Suggestion: Don't use object manager directly in your code as its not a best practice. You need to inject the product model class to your respective class then use it.