Magento 2 – get simple products of configurable product
In this tutorial I show you how to get simple products of configurable product. You may need this on frontend pages, if you want to display product information that is only stored in simple product attributes. You may also need this to show how many simple products are associated to a configurable.
Magento 2 – get simple products of configurable product
Magento is the most used open source e-commerce system for many reasons. One of them is the use of configurable products, which can be configured by yourself. You can decide on which attribute this simple to configurable product association is based. You can use one attribute or a whole bunch of them (color, size, …). Only expansive shop systems offer you an equal system.
Sample code
The following sample code demonstrates how to load a configurable product by object manager and get all child products (associated simple products) as an array.
1 2 3 4 5 6 7 | $configProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id); $_children = $configProduct->getTypeInstance()->getUsedProducts($configProduct); foreach ($_children as $child){ echo "Here are your child Product Ids ".$child->getID()."\n"; } echo "count: ".count($_children); |
First, we load a configurable product by its product_id by object manager. Please consider to use Magento 2 injections to do this instead! You can get an array of associated simple products by simply calling getUsedProducts() from objects type instance. The sample code prints out simple product ids and the sum of simple products.
Background
Only configurable products are visible in your frontend. You may have hundred or more simple products associated to one single configurable product. You need one simple for each configurable attribute combinations. Depending on the number of configurable attributes and attribute options, this may be a huge number. Based on your data it is possible, beside you configurable attributes, that other attributes vary for each simple. If you need to display such data in frontend before selection of a simple one, you need the code above to get it!
Conclusion
I showed you how to get simple products of configurable product. This is the common way to do it in Magento 2.
1 Response
[…] + View Here […]