Grouped products are only one of many Magento 2 product types. What is special about them is that they consist of simple products that can be purchased separately or as a group. Moreover, grouped products don't have a price, since it's defined by its component products.
Of course, you can create grouped products using the admin panel. However, you might also be looking for a programmatic way to perform this task.
If you want to know how to create grouped products programmatically, you've landed on the right page.
To create a grouped product in Magento programmatically use the following code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(\Magento\Framework\App\State::class);
$state->setAreaCode('frontend');
try {
$product = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterface::class);
$product->setTypeId(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE)
->setAttributeSetId(4)
->setName('Grouped Product')
->setSku('Grouped Product')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$childrenIds = array(1, 2);
$associated = array();
$position = 0;
foreach ($childrenIds as $productId) {
$position++;
$linkedProduct = $productRepository->getById($productId);
$productLink = $objectManager->create(\Magento\Catalog\Api\Data\ProductLinkInterface::class);
$productLink->setSku($product->getSku())
->setLinkType('associated')
->setLinkedProductSku($linkedProduct->getSku())
->setLinkedProductType($linkedProduct->getTypeId())
->setPosition($position)
->getExtensionAttributes()
->setQty(1);
$associated[] = $productLink;
}
$product->setProductLinks($associated);
$productRepository->save($product);
echo 'success';
} catch (\Exception $e) {
$objectManager->get(\Psr\Log\LoggerInterface::class)->info($e->getMessage());
echo $e->getMessage();
}
You can use this guide to create grouped products in Magento programmatically faster and optimize the inventory management in your store.
But it doesn't mean that you have to stop here. You can go further and learn how to create other types of products, like bundle or configurable products.