Create Bundle Product Programmatically in Magento 2

Steps to Create Bundle Product Programmatically in Magento 2

In this tutorial, I will explain how to create bundle product programmatically in Magento 2. The Bundle Product is a customizable product that can build your own. Each item in the bundle product can be based on these two product types: simple product and virtual product.

In this, you can set a dynamic or fixed value for the bundle product. But, if we perform from the admin panel and create the product from the admin panel it takes a little bit long time. At that time, the script will be helpful for you to create a bundle product quickly.

Magento 2 bundled product basically lets you “build your own” customized product.

Each bundled product can be either a simple product or a grouped product that can be either purchased individually or as a combo.

And in this article, we will show you exactly how to create a bundled product programmatically in Magento 2.

When we need to create a bundle product using a script instead of the admin panel. Then, how we can create it by script?

Let’s create the script for that. First of all, create bundleproduct.php file at your Magento’s root folder and add this below code (It’s working code). 

<?php

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product = $objectManager->create('Magento\Catalog\Model\Product');

try {
    $product->setName('Bundle Product'); // Set Product Name
    $product->setTypeId('bundle'); // Set Product Type Id
    $product->setAttributeSetId(11); // Set Attribute Set ID
    $product->setSku('bundle-product'); // Set SKU
    $product->setWebsiteIds([1]); // Set Website Ids
    $product->setVisibility(4); // Set Visibility
    $product->setImage('/bundle/test.jpg'); // Image Path
    $product->setSmallImage('/bundle/test.jpg'); // Small Image Path
    $product->setThumbnail('/bundle/test.jpg'); // Thumbnail Image Path
    $product->setPriceType(0);
    $product->setPriceView(0);
    $product->save();
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
    // Set bundle product items
    $product->setBundleOptionsData(
        [
            [
                'title' => 'Bundle Product Items 1',
                'default_title' => 'Bundle Product Items 1',
                'type' => 'select',
                'required' => 1,
                'delete' => '',
            ],
            [
                'title' => 'Bundle Product Items 2',
                'default_title' => 'Bundle Product Items 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');
                $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'])
                        {
                            /** @var \Magento\Bundle\Api\Data\LinkInterface$link */
                            $link = $objectManager->create('Magento\Bundle\Api\Data\LinkInterface');
                            $link->setData($linkData);
                            $linkProduct = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface')->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 "Product Created Successfully";
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

That’s it !!

Additionally, the static details can be set based on your requirements. If you are planning to create multiple products programmatically by the script, you can use this script and customise code for numerous products create.

Now, execute this file at frontend side : {baseUrl}/bundleproduct.php

Feel free to reach us out in case we missed out something. We’ll be glad to help.

Magento 2 Migration Services

Tags