Magento 2 Complete Guide to add a product programmatically

There are several scenario when we might need to add our product programmatically in Magento. This blog-post will provide you a detail guide to add the product in database programmatically.
You can follow below posts for creating different product of various type:-

Adding a simple product

Below code will add a new product to magento 2 with SKU as “W3PRO1”, comments are properly given to make the code self-explainable. We have added product with ‘default’ attribute set.

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
        $product = $objectManager->create('\Magento\Catalog\Model\Product');
        $product->setSku('W3PRO1'); // Set your sku here
        $product->setName('Sample Product'); // Name of Product
        $product->setAttributeSetId(4); // Attribute set id
        $product->setStatus(1); // Status on product enabled/ disabled 1/0
        $product->setProductHasWeight(1); // if product has weight
        $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' => 99
                         )
                     );
        $product->setNewsFromDate('11-11-2017'); // set the data from which product will be marked as new
        $product->setNewsToDate('11-12-2017'); // set the data till when product will be marked as new
        $product->setCountryOfManufacture('AL'); // Set country of manufacture

        $product->save();
Note: It is not recommended to create object using object manager, you should inject dependency through constructor and then further use them for object creation 

Add Related, Upsell and Crosssell to product

Above code is the basic example for adding product, now if we want to add related, upsell or crosssell product then we need to add below code before saving the products. Below we have just given example for related. Crosssell and upsell will also be created in the same way.

$this->_productLink = $objectManager->create('\Magento\Catalog\Api\Data\ProductLinkInterfaceFactory ');
$skuLinks = '24-MB01,24-MB04,24-MB03';
 $skuLinks = explode(",",$skuLinks);
foreach($skuLinks as $skuLink) {
    $linkData = $this->_productLink->create();
    $linkData->setSku($product->getSku())
             ->setLinkedProductSku($skuLink)
             ->setLinkType("related");
    $linkDataAll[] = $linkData;
}
if($linkDataAll) {
   /* this will set related products detail, similarly we can add upsell and crossell */
   $product->setProductLinks($linkDataAll); 
}

Add Customizable Options

$this->_productCustomOption = $objectManager->create('\Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory');

$customOption = $this->_productCustomOption->create()->setTitle('Text')
                     ->setType('area')
                     ->setIsRequire(true)
                     ->setSortOrder(1)
                     ->setPrice(1.00)
                     ->setPriceType('fixed')
                     ->setMaxCharacters(50)
                     ->setProductSku($product->getSku());

$customOptions[] = $customOption;
$product->setOptions($customOptions);

Add website design, Schedule design update, gift options

$product->setWebsiteIds(array(1));  //add website id

/* Add design Attribute*/
$product->setPageLayout('1column');  
$product->setOptionsContainer('container1');
$product->setCustomLayoutUpdate('');

/* Add Schedule Design Update*/
$product->setCustomDesignFrom('1-6-2017');
$product->setCustomDesignTo('1-6-2017');
$product->setCustomDesign(1);
$product->setCustomLayout('1column');

/* Add Gift Options*/
 $product->setGiftMessageAvailable(1);

Leave a Comment.