Magento 2 create product programmatically - Simple, Configurable, Downloadable, Bundle

Today I will show you a code snippet that allows creating many types of products including Simple, Configurable, Bundle, and Downloadable perfectly.

Similar to creating a new customer in Magento 2, online store owners can create products programmatically by implementing with the code instead of that you must waste time adding the new products through admin control. Today, on the topic Magento 2 create product programmatically, I will show you a code snippet that allows creating many types of products (simple, configurable, and downloadable) perfectly.

Overview of product types in Magento 2

In this tutorial you can create the following types of products:

  • Simple
  • Configurable
  • Downloadable
  • Bundle

Let’s get an idea about 4 types of products you can create in a Magento 2 store.

Simple product is a physical item with a single SKU. This kind of product has no selectable variations. You can’t choose sizes, colors, or any product attributes on items of this product type.

In a Magento 2 store, simple products can be sold individually or in other product types, such as configurable and bundle products. Configurable product is a more complicated than simple products. That’s why creating a configurable product takes more time than that of a simple product.

Configurable products have different product options to choose from. Each combination of product options has an individual SKU. With this product type, first, you need to think about creating attributes for your products.

Downloadable product has no physical form, and you have nothing to do with manufacturing, packaging, and delivery. This kind of product allows you to sell apps, software products, digital products, ebooks, music, etc. Magento extensions are also downloadable products.

Learn about how to create downloadable products in Magento 2 here.

Bundle product is created to have various options in shopping with a collection of simple products. You can add more items to a bundle product.

Learn about how to create bundle products in Magento 2 here.

4 Steps to create configurable product programmatically

Step 1: To create Simple product programmatically

$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); // visibilty 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 product

You can add multiple images into media gallary of this 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 to the product

This can be applied for other product type such as Virtual Products, Downloadable Product, etc.

// 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);
}

With this script code, you should take some notes to create simple, configurable, downloadable products like the following:

  • To create the simple product, you need to pass the weight setting.
  • To create the configurable product, it is required to combine between associated products current product.
  • To create the downloadable product, it is required to insert the download link into the current product. If not, you will generate virtual or simple product.

Step 4: How to assign associated products

This is a tip to help you create configurable products. Please using the snippet below:

$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();

If there is the same assignment (the associated product is already assigned to configurable product), the command will run error.

Conclusion

It’s important to create products correctly in Magento 2. I hope this tutorial is useful for you to make everything work in the right way. Share it with your friends if they are also in need. Thanks for reading.

Related Topics

Image Description
Sam is the CEO & co-founder of Mageplaza, a company established to support Magento merchants with different powerful tools and resources. Sam Nguyen is also the CEO & founder of Avada Commerce, an e-commerce solution provider headquartered in Singapore – aiming to support more than a million online businesses to grow and develop.

People also searched for

  • magento 2 product programmatically
  • create product programmatically in magento 2
  • update product programmatically magento 2
  • save product programmatically magento 2
  • delete product programmatically magento 2
  • create product programmatically drupal commerce
  • add product programmatically woocommerce magento 2
  • magento 2 create product programmatically
  • magento 2 create product programmatically in woocommerce
  • magento 2 duplicate product programmatically
  • create product attribute programmatically magento 2
  • update product attribute programmatically magento 2
  • magento 2 product attribute programmatically
  • magento 2 add product attribute programmatically
  • programmatically add product to cart in magento 2
  • add product programmatically magento 2
  • magento 2 delete product attribute programmatically
  • magento 2 get product attribute programmatically
  • magento 2 programmatically add product to cart drupal commerce
  • 2.3.x, 2.4.x
x