How to Create Simple Product Programmatically in Magento 2

Creating products programmatically in Magento 2 can be a time-saver, especially if you’re dealing with bulk product imports or automating the catalog management process. In this article, we will walk through how to create a simple product programmatically in Magento 2.

This method is particularly useful for developers or store owners who want to automate product creation without manually entering each product into the admin panel.

What is a Simple Product in Magento 2?

A simple product in Magento 2 is the most basic type of product you can create. It doesn’t have any variations (like size or color) and is typically used for products that are sold individually without any custom options. Examples include single items like books, electronics, or clothing.

Why Need to Create Products Programmatically?

Creating products programmatically can save time and reduce the risk of human error. This is especially useful when dealing with a large product catalog or when integrating Magento 2 with external systems, such as ERPs or custom inventory management systems. Automating product creation can also streamline tasks such as data migrations or batch imports.

Prerequisites for Creating Products Programmatically in Magento 2

Before creating products programmatically, ensure you have:

  • Magento 2 is installed and running on your server
  • Access to the Magento root directory and the ability to run PHP scripts
  • A basic understanding of PHP programming
  • A code editor to write your script

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

Programmatically creating simple products in Magento 2 can streamline your catalog management and save time, especially for larger stores. By using the steps outlined in this guide, you can automate product creation and avoid the tedious process of manually entering products into your store.

Whether you’re creating one product or hundreds, this method offers a flexible way to manage your Magento 2 store efficiently. Always remember to test your script thoroughly in a development environment before applying it to a live store.

Related Topics

Image Description
With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.

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