How to create bundle product in Magento 2 programmatically ?

Welcome to Kishan Savaliya's Magento 2 Blog.In this blog post, I will explain how to create a bundle product in Magento 2 programmatically. We can create bundle product using backend too but in some case if you need to create bundle products again and again then if you will create product from backend then it will take more time and instead of that you can do that easily with simple root script file, it will save your time and that is quite easy to do.

Bundle items can be simple or virtual products without custom options.

Bundle items can be shipped together or separately.

So let's start.. Move into your Magento 2 root directory and create below file there..

create_bundleproduct.php

Content for this file is..

<?php
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$objectManager->get(Magento\Framework\App\State::class)->setAreaCode('frontend');
$product = $objectManager->create(Magento\Catalog\Model\Product::class);

try {
    $product->setTypeId(\Magento\Bundle\Model\Product\Type::TYPE_CODE);
    $product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
    $product->setAttributeSetId(4); //Set your attribute set ID, I used 4 because I have default Luma theme and I want to use Default attribute set and it's attribute ID is 4, find your ID and set here.
    $product->setName('Bundle Product name');
    $product->setSku('bundle-product-sku');
    $product->setUrlKey('bundle-product-url-key');
    $product->setDescription('<p>Bundle Product Description</p>');
    $product->setShortDescription('<p>Bundle Product Short Description</p>');
    $product->setWebsiteIds([1]); //Find your website ID and set that ID instead of 1 in array
    $product->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH); //To display bundle product in frontend you can set visibility to catalog, search

    $product->setPriceType(0);
    $product->setPriceView(0);

    $product->save();

    $product = $objectManager->create(Magento\Catalog\Model\Product::class)->load($product->getId());
    // Set bundle product items
    $product->setBundleOptionsData(
        [
            [
                'title' => 'Item 1',
                'default_title' => 'Item 1',
                'type' => 'select',
                'required' => 1,
                'delete' => '',
            ],
            [
                'title' => 'Item 2',
                'default_title' => 'Item 2',
                'type' => 'select',
                'required' => 1,
                'delete' => '',
            ]
        ]
    )->setBundleSelectionsData(
        [
            [
                ['product_id' => 1, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
                ['product_id' => 3, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
            ],
            [
                ['product_id' => 2, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
                ['product_id' => 4, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
            ],
        ]
    );
    if ($product->getBundleOptionsData())
    {
        $options = [];
        foreach ($product->getBundleOptionsData() as $key => $optionData)
        {
            if (!(bool) $optionData['delete'])
            {
                $option = $objectManager->create(Magento\Bundle\Api\Data\OptionInterface::class);
                $option->setData($optionData);
                $option->setSku($product->getSku());
                $option->setOptionId(null);
                $links = [];
                $bundleLinks = $product->getBundleSelectionsData();
                if (!empty($bundleLinks[$key]))
                {
                    foreach ($bundleLinks[$key] as $linkData)
                    {
                        if (!(bool) $linkData['delete'])
                        {
                            $link = $objectManager->create(Magento\Bundle\Api\Data\LinkInterface::class);
                            $link->setData($linkData);
                            $linkProduct = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class)->getById($linkData['product_id']);
                            $link->setSku($linkProduct->getSku());
                            $link->setQty($linkData['selection_qty']);
                            if (isset($linkData['selection_can_change_qty']))
                            {
                                $link->setCanChangeQuantity($linkData['selection_can_change_qty']);
                            }
                            $links[] = $link;
                        }
                    }
                    $option->setProductLinks($links);
                    $options[] = $option;
                }
            }
        }
        $extension = $product->getExtensionAttributes();
        $extension->setBundleProductOptions($options);
        $product->setExtensionAttributes($extension);
    }
    $product->save();
    
    if($product->getId()){
        echo "Bundle Product created successfully.";
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

You can change above content based on your requiremrent. You can simply run below URL in browser it'll create bundle product in your Magento.

{{magento_base_url}}/create_bundleproduct.php

That's it.


Hope you may like this article and can understand this easily. You can add comments below in case if you have any questions regarding this article or if I missed anything here. I will check and get back to you with proper solution.

If you enjoyed this blog post, share it with friends!