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

Similarly to the creating a new customers in Magento 2, online store owners can create product 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 will show you a code snippet that allows doing the creating many types of product (simple, configurable, and downloadable) perfectly.

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

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

## Add custom options to the product This can be applied for other product type such as Virtual, 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 as 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.

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.



Next tutorial:

Module Development Series



Enjoyed the tutorial? Spread it to your friends!

magento-2-tutorial
create
product
programmatically

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

Please leave comments if you have any questions, feedbacks.

Module Development

You also may like these Magento 2 Extensions

One Step Checkout

$199
10 reviews

Layered Navigation

$99
12 reviews

SEO

FREE
no review

Shop By Brand

$99
3 reviews

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