Magento 2:- Add a bundled product programmatically

Follow my previous blogpost to create a simple product with magento that will give you a basic idea of creating products. In this blogpost we will continue from that post only. So to create product as bundled, we need to set two more attribute value i.e, price_view and price_type.
In previous post code you also need to change typeId as bundles. After creating a product with type bundled we have to add a link and option information for the product.
Firstly lets see the modified attribute:-

 $product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); 
 $product->setPriceType(1); 
 $product->setPriceView(1);

To add a link use the below code.

$link = $objectManager->create(\Magento\Bundle\Api\Data\LinkInterface::class);
$link->setPosition(0);
$link->setSku('MH01-XS-Orange');
$link->setIsDefault(false);
$link->getQty(1);
$link->setPrice(12);
$link->setPriceType(\Magento\Bundle\Api\Data\LinkInterface::PRICE_TYPE_FIXED);
 

To add link to option add below code:-

$optionRepository = $objectManager->create(\Magento\Bundle\Api\ProductOptionRepositoryInterface::class);
$option = $objectManager->create(\Magento\Bundle\Api\Data\OptionInterface::class);
$option->setTitle('Size');
$option->setType('radio');
$option->setRequired(true);
$option->setPosition(1);
$option->setProductLinks(array($link));
$optionRepository->save($product, $option);

In below image you can see the data added to our product:-

Leave a Comment.