Site icon MageComp Blog

How to Create Bundled Product Programmatically in Magento 2

Hello Magento Folks,

Welcome to Create Product Programmatically series where I will illustrate How to Create Bundled Product Programmatically in Magento 2. Basically, a bundle product is considered similar to a simple product or a grouped product which are purchased as a combo or group. Check out all the product types in detail at Magento 2 Product Types: All You Need to Know Guide. Check out the below code to create bundled products programmatically in Magento 2 store.

Mainly we can create 6 types of products Programmatically in Magento 2:

Steps to Create Bundled Product Programmatically in Magento 2:

Step 1: Firstly, create a bundle_product.php file in the Magento root directory and add the below given code to it.

<?php

use Magento\Framework\AppInterface;

try {
    require_once __DIR__ . '/app/bootstrap.php';
} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try {
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('Magento\Framework\App\State');
    $appState->setAreaCode('frontend');
    $bundle_product = $objectManager->create('Magento\Catalog\Model\Product');
    $bundle_product->setStatus(1); // status enabled/disabled 1/0
    $bundle_product->setName('Bundle Product'); // Set Your Bundle Name of Product
    $bundle_product->setTypeId('bundle'); // Set Product Type Id (simple/virtual/downloadable/configurable/grouped/bundle)
    $bundle_product->setAttributeSetId(4); // Set Attribute Set ID
    $bundle_product->setSku('bundle_product_sku'); // Set Bundle Product SKU
    $bundle_product->setSkuType(1); // Yes (0) / No (1)
    $bundle_product->setWebsiteIds(array(1)); // Set Website Ids
    $bundle_product->setVisibility(4);  // visibility of product (Not Visible Individually (1) / Catalog (2)/ Search (3)/ Catalog, Search(4))
    $bundle_product->setShipmentType(0); // Together (0) / Separately (1)
    $category_id = array(2, 3);
    $bundle_product->setCategoryIds($category_id);
    $bundle_product->setStockData(
        [
            'use_config_manage_stock' => 1,
            'manage_stock' => 1,
            'is_in_stock' => 1,
        ]
    );
    $bundle_product->save();
    $bundle_product = $objectManager->create('Magento\Catalog\Model\Product')->load($bundle_product->getId());

    // Set Bundle Options Data
    $bundle_product->setBundleOptionsData(
        [
            [
                'title' => 'Bundle Product Items title 1',
                'default_title' => 'Bundle Product Items title 1',
                'type' => 'radio',
                'required' => 1,
                'delete' => '',
            ],
            [
                'title' => 'Bundle Product Items title 2',
                'default_title' => 'Bundle Product Items title 2',
                'type' => 'checkbox',
                'required' => 1,
                'delete' => '',
            ]
        ]
    )->setBundleSelectionsData(
        [
            [
                ['product_id' => 1, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
                ['product_id' => 9, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
            ],
            [
                ['product_id' => 34, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
                ['product_id' => 35, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
            ],
        ]
    );
    // setBundleSelectionsData set your Product Id
    if ($bundle_product->getBundleOptionsData()) {
        $options = [];
        foreach ($bundle_product->getBundleOptionsData() as $key => $option_data) {
            if (!(bool)$option_data['delete']) {
                $option = $objectManager->create('Magento\Bundle\Api\Data\OptionInterface');
                $option->setData($option_data);
                $option->setSku($bundle_product->getSku());
                $option->setOptionId(null);
                $links_array = [];
                $bundle_links_data = $bundle_product->getBundleSelectionsData();
                if (!empty($bundle_links_data[$key])) {
                    foreach ($bundle_links_data[$key] as $linkdata) {
                        if (!(bool)$linkdata['delete']) {
                            $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_array[] = $link;
                        }
                    }
                    $option->setProductLinks($links_array);
                    $options[] = $option;
                }
            }
        }
        $extension_attribute = $bundle_product->getExtensionAttributes();
        $extension_attribute->setBundleProductOptions($options);
        $bundle_product->setExtensionAttributes($extension_attribute);
    }
    $bundle_product->save();
    if ($bundle_product->getId()) {
        echo "Bundle Product Created Successfully.";
    }
}catch (\Exception $e) {
    echo $e->getMessage();
}

Step 2: After the above step add run below URL.

https://yourdomain.com/bundle_product.php

Wrap Up:

Hopefully, all are able to Create Bundled Product Programmatically in Magento 2 using the code above. In case you come across any errors then comment down your queries in the comment section below I will solve them there. You can also take the help of our certified Magento Developers

Share the article with your Friends.

Happy Reading!

Exit mobile version