Configurable products bring many benefits to an e-commerce store, both B2C and B2B. However, generating one by one may take a lot of time if you have an extensive catalog. In this case, creating configurable product programmatically can be a solution for Magento 2 store owners.
Programmatically creating items allows developers to quickly and easily set up online stores. When you need different colors and sizes for the same product, you’ll need to create a configurable product in Magento 2.
So let’s get started with this Magento 2 create configurable product programmatically guide.
Who Should Create Configurable Product in Magento 2 Programmatically?
Table of Contents
Configurable products are a must-have for many firms since they allow visitors to examine the product’s choices. Magento comes with the ability to build and manage configurable products by default, with features such as flexible pricing, inventory management, delivery terms, and promotions.
Follow this detailed guide that walks you through the simple steps to create configurable products in Magento Admin Panel
However, when done manually, it takes time and effort to link multiple simple products to a configurable one. Thankfully, programmatically creating products helps developers set up online stores quicker.
This way can help save a lot of effort for those with an extensive catalog size.
Consider creating configurable products programmatically in Magento 2 if you have coding knowledge. On the contrary, instead of taking risks without coding experience, you can seek help from reputable developers.
Check out our guide below:
How Do You Create Configurable Products in Magento 2 Programmatically?
Step 1: Create a Simple Product Programmatically
Instead of having to do each step in the backend dashboard as usual, in a programmatic way, you need to create a file in the Magento root directory and insert the following code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager $product = $objectManager->create('\Magento\Catalog\Model\Product'); $product->setSku('my-sku'); // Set your sku here $product->setName('Sample Simple Product'); // Name of Product $product->setAttributeSetId(4); // Attribute set id $product->setStatus(1); // Status on product enabled/ disabled 1/0 $product->setWeight(10); // weight of product $product->setVisibility(4); // visibility of product (catalog / search / catalog, search / Not visible individually) $product->setTaxClassId(0); // Tax class id $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable) $product->setPrice(100); // price of product $product->setStockData( array( 'use_config_manage_stock' => 0, 'manage_stock' => 1, 'is_in_stock' => 1, 'qty' => 999999999 ) ); $product->save();
Step 2: Add an Image to the Product
After creating simple product, you need to add image to the product:
// Adding Image to product $imagePath = "sample.jpg"; // path of the image $product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false); $product->save();
Step 3: Add Custom Options (Children Product) to the Product (Parent Product)
Next, create custom options and assign a simple one to them. Combining associated products with the current product is necessary to produce the configurable product.
// Adding Custom option to product $options = array( array( "sort_order" => 1, "title" => "Custom Option 1", "price_type" => "fixed", "price" => "10", "type" => "field", "is_require" => 0 ), array( "sort_order" => 2, "title" => "Custom Option 2", "price_type" => "fixed", "price" => "20", "type" => "field", "is_require" => 0 ) ); foreach ($options as $arrayOption) { $product->setHasOptions(1); $product->getResource()->save($product); $option = $objectManager->create('\Magento\Catalog\Model\Product\Option') ->setProductId($product->getId()) ->setStoreId($product->getStoreId()) ->addData($arrayOption); $option->save(); $product->addOption($option); }
Step 4: Assign Associated Products
To build a configurable product, follow the steps above and then execute the URL listed below: https://yourdomain.com/configurable_product.php
Follow this snippet to assign associated products to create configurable products in Magento 2 programmatically.
$productId = 12; // Configurable Product Id $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load Configurable Product $attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute'); $position = 0; $attributes = array(134, 135); // Super Attribute Ids Used To Create Configurable Product $associatedProductIds = array(2,4,5,6); //Product Ids Of Associated Products foreach ($attributes as $attributeId) { $data = array('attribute_id' => $attributeId, 'product_id' => $productId, 'position' => $position); $position++; $attributeModel->setData($data)->save(); } $product->setTypeId("configurable"); // Setting Product Type As Configurable $product->setAffectConfigurableProductAttributes(4); $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $product); $product->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id $product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products $product->setCanSaveConfigurableAttributes(true); $product->save();
Note that the command will fail if there is a duplicate assignment (the corresponding product is already allocated to a customizable product).
Tips for Simplify Configurable Products
The guide for Magento 2 create configurable product programmatically has extremely minimal capabilities and may be found in practically every retailer nowadays. So, what if you need some extra features? What if you’re a retailer who wants to boost client loyalty and give them a better shopping experience?
In such instances, Magento 2 extensions can be a savior. Magento 2 Improved Configurable Products by BSS Commerce is one of these additions.
The extension is a complete enhancement solution that, once loaded, improves the entire aesthetic and performance of configurable products while also providing a better shopping experience for clients.
The following are some tips to optimize the configurable product in Magento 2.
Product Page Enhancements
Magento’s default selection option display for configurable products makes it inconvenient for customers to order and review products.
Before adding a child product to the cart, customers must select each custom option and quantity. As a result, if they want many things, they cannot add numerous simple products to the shopping cart at once.
However, Magento 2 Simple Details on Configurable Product can give your product a unique identity and display details of all children items on one page. Hence, customers may quickly locate the appropriate child product based on color, size, and other characteristics.
As you can see, the extension covers practically every aspect of the product page and adds many useful features.
Dynamic Content Update
You need this if you’re a supplier or manage a store where clients can buy many products and product variations simultaneously.
It is difficult to add all essential products to the cart when shopping for various product versions.
Thus, a dynamic content update will improve the shopping experience. Customers return to the stores where they feel most at ease. Besides, it also helps to increase the conversion rate due to precisely targeted advertisements.
With Magento 2 Configurable Product Matrix View, your customers know the variety they choose.
Second, because variations can differ, it’s critical to include a separate description for each Configurable Product variation.
Thirdly, the module, in addition to the core Magento 2 product pricing, supports advanced tiered prices and calculates the total price of a product immediately on the product page.
Pro Tips for B2B Store
Configurable products, even though they require more SKUs and may take longer to set up at first, give long-term benefits for both B2B business owners and customers.
The following are some of the most significant advantages of adopting configurable products for B2B stores:
- Firstly, bulk B2B orders can be created and processed fast and efficiently. By leveraging Magento 2 Configurable Product Wholesale Display, wholesale customers can add all chosen items to the cart at once. As a result, you can enhance the shopping experience, save time, etc.
- Secondly, it allows for the easy implementation and display of tiered pricing.
- Thirdly, a configurable product’s supply of items can be tracked for different item combinations.
- Lastly, the product pages appear well-designed. Magento 2 Customizable Product Wholesale Display will reduce the number of children products presented in the grid table by just displaying alternatives for one attribute on the table, allowing consumers to have a better perspective and place orders without being confused or making mistakes. As a result, the module will undoubtedly improve the appearance of configurable items.
Conclusion
Hopefully, you can easily practice with the above guide of Magento 2 create configurable product programmatically. Clear cache and reindex, as Magento requires, to see output on the front end of your Magento 2 store.
As mentioned above, if you have no coding experience, you should carefully consider it. Otherwise, consider BSS Commerce third-party modules for more accessible display and management.
BSS Commerce is the global all-in-one eCommerce agency with 11+ years of working experience in the field. If you are a Magento store owner looking for an exceptional Magento website development service, our highly-qualified experts are committed to delivering it to you.