{"id":848,"date":"2020-02-27T04:02:17","date_gmt":"2020-02-27T04:02:17","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/2020\/02\/27\/programmatically-create-bundled-product-in-magento-2\/"},"modified":"2025-05-22T14:54:07","modified_gmt":"2025-05-22T09:24:07","slug":"programmatically-create-bundled-product-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/programmatically-create-bundled-product-in-magento-2\/","title":{"rendered":"Learn to Programmatically Create Bundled Product In Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/experienceleague.adobe.com\/en\/docs\/commerce-admin\/catalog\/products\/types\/product-create-bundle\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2 Bundle Product<\/a>&nbsp;is simply \u201cbuild your own\u201d customizable product.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are&nbsp;<a href=\"https:\/\/experienceleague.adobe.com\/en\/docs\/commerce-admin\/catalog\/products\/product-create\" target=\"_blank\" rel=\"noreferrer noopener\">six product types<\/a>&nbsp;in Magento 2:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Simple Product<\/li>\n\n\n\n<li>Configurable Product<\/li>\n\n\n\n<li>Grouped Product<\/li>\n\n\n\n<li>Virtual Product<\/li>\n\n\n\n<li>Bundle Product<\/li>\n\n\n\n<li>Downloadable Product<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Each item in a bundle can be either a simple product or a grouped product and thus, can be bought individually or as a combo. The perfect example of a bundle product is a corporate menswear combo including a shirt, formal pants, tie, blazer, etc.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">On click of \u201cCustomize\u201d or \u201cAdd to Cart\u201d button, the option for the selection is displayed.&nbsp; The bundle can consist of varied products and hence, the SKU, price, and weight is set to either dynamic or fixed value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s the code to&nbsp;<em><strong>programmatically create bundled product in Magento 2<\/strong><\/em>&nbsp;store easily!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Method to programmatically create bundled product in Magento 2:<\/h2>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try {\n    $bundleProduct = \\Magento\\Framework\\App\\ObjectManager::getInstance()\n->create(\\Magento\\Catalog\\Api\\Data\\ProductInterface::class);\n    $bundleProduct\n        ->setStoreId(0)\/\/you can set data in store scope\n        ->setWebsiteIds(array(1))\/\/website ID the product is assigned to, as an array\n        ->setAttributeSetId(4)\/\/ID of a attribute set named 'default'\n        ->setTypeId('bundle')\/\/product type\n        ->setCreatedAt(strtotime('now'))\/\/product creation time\n\/\/    ->setUpdatedAt(strtotime('now')) \/\/product update time\n        ->setSkuType(0)\/\/SKU type (0 - dynamic, 1 - fixed)\n        ->setSku('bundlet1')\/\/SKU\n        ->setName('Test Bundle Product1')\/\/product name\n        ->setWeightType(0)\/\/weight type (0 - dynamic, 1 - fixed)\n\/\/        ->setWeight(4.0000)\n        ->setShipmentType(0)\/\/shipment type (0 - together, 1 - separately)\n        ->setStatus(1)\/\/product status (1 - enabled, 2 - disabled)\n        ->setVisibility(\\Magento\\Catalog\\Model\\Product\\Visibility::VISIBILITY_BOTH)\/\/catalog and search visibility\n        ->setManufacturer(83)\/\/manufacturer id\n        ->setColor(24)\n        ->setNewsFromDate('01\/01\/2020')\/\/product set as new from\n        ->setNewsToDate('12\/31\/2020')\/\/product set as new to\n        ->setCountryOfManufacture('IN')\/\/country of manufacture (2-letter country code)\n        ->setPriceType(0)\/\/price type (0 - dynamic, 1 - fixed)\n        ->setPriceView(0)\/\/price view (0 - price range, 1 - as low as)\n        ->setSpecialPrice(50.00)\/\/special price in form 11.22 special price in percentage of original price\n        ->setSpecialFromDate('01\/01\/2020')\/\/special price from (MM-DD-YYYY)\n        ->setSpecialToDate('12\/31\/2020')\/\/special price to (MM-DD-YYYY)\n        \/\/only available if price type is 'fixed'\/\n\/\/        ->setPrice(11.22) \/\/price, works only if price type is fixed\n\/\/        ->setCost(22.33) \/\/price in form 11.22\n\/\/        ->setMsrpEnabled(1) \/\/enable MAP\n\/\/        ->setMsrpDisplayActualPriceType(1) \/\/display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)\n\/\/        ->setMsrp(99.99) \/\/Manufacturer's Suggested Retail Price\n\/\/        ->setTaxClassId(4) \/\/tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)\n        \/\/only available if price type is 'fixed'\/\n        ->setMetaTitle('test meta title 2')\n        ->setMetaKeyword('test meta keyword 2')\n        ->setMetaDescription('test meta description 2')\n        ->setDescription('This is a long description')\n        ->setShortDescription('This is a short description')\n        ->setMediaGallery(array('images' => array(), 'values' => array()))\/\/media gallery initialization\n        ->setStockData(array(\n                'use_config_manage_stock' => 1, \/\/'Use config settings' checkbox\n                'manage_stock' => 1, \/\/manage stock\n                'is_in_stock' => 1, \/\/Stock Availability\n            )\n        )\n        ->setCategoryIds(array(4, 10)); \/\/assign product to categories\n\n    \/\/ Set bundle product items\n    $bundleProduct->setBundleOptionsData(\n        [\n            [\n                'title' => 'Bundle Test Items 1',\n                'default_title' => 'Bundle Test Items 1',\n                'type' => 'select',\n                'required' => 1,\n                'delete' => '',\n            ],\n            [\n                'title' => 'Bundle Test Items 2',\n                'default_title' => 'Bundle Test Items 2',\n                'type' => 'select',\n                'required' => 1,\n                'delete' => '',\n            ]\n        ]\n    )->setBundleSelectionsData(\n        [\n            [\n                ['product_id' => 1, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],\n                ['product_id' => 3, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],\n            ],\n            [\n                ['product_id' => 2, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],\n                ['product_id' => 4, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],\n            ],\n        ]\n    );\n    if ($bundleProduct->getBundleOptionsData())\n    {\n        $options = [];\n        foreach ($bundleProduct->getBundleOptionsData() as $key => $optionData)\n        {\n            if (!(bool) $optionData['delete'])\n            {\n                $option = $objectManager->create('Magento\\Bundle\\Api\\Data\\OptionInterface');\n                $option->setData($optionData);\n                $option->setSku($bundleProduct->getSku());\n                $option->setOptionId(null);\n\n                $links = [];\n                $bundleLinks = $bundleProduct->getBundleSelectionsData();\n                if (!empty($bundleLinks[$key]))\n                {\n                    foreach ($bundleLinks[$key] as $linkData)\n                    {\n                        if (!(bool) $linkData['delete'])\n                        {\n                            \/** @var \\Magento\\Bundle\\Api\\Data\\LinkInterface$link *\/\n                            $link = $objectManager->create('Magento\\Bundle\\Api\\Data\\LinkInterface');\n                            $link->setData($linkData);\n                            $linkProduct = $objectManager->get('\\Magento\\Catalog\\Api\\ProductRepositoryInterface')->getById($linkData['product_id']);\n                            $link->setSku($linkProduct->getSku());\n                            $link->setQty($linkData['selection_qty']);\n                            if (isset($linkData['selection_can_change_qty']))\n                            {\n                                $link->setCanChangeQuantity($linkData['selection_can_change_qty']);\n                            }\n                            $links[] = $link;\n                        }\n                    }\n                    $option->setProductLinks($links);\n                    $options[] = $option;\n                }\n            }\n        }\n        $extension = $bundleProduct->getExtensionAttributes();\n        $extension->setBundleProductOptions($options);\n        $bundleProduct->setExtensionAttributes($extension);\n    }\n    $bundleProduct->save();\n    echo 'success';\n} catch (\\Exception $e) {\n    \\Magento\\Framework\\App\\ObjectManager::getInstance()->get('Psr\\Log\\LoggerInterface')->info($e->getMessage());\n    echo $e->getMessage();\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That\u2019s it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do share the post with Magento peeps via social media.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Magento 2 Bundle Product&nbsp;is simply \u201cbuild your own\u201d customizable product. There are&nbsp;six product types&nbsp;in Magento 2: Each item in a bundle can be either a&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-848","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/848","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=848"}],"version-history":[{"count":3,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/848\/revisions"}],"predecessor-version":[{"id":15064,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/848\/revisions\/15064"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=848"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=848"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=848"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}