Magento 2 : Programmatically creating Magento product

Posted On: April 30, 2017

In a development process, you need some testing data you can use. Magento supplies you with it’s default Sample Data that contains products.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create(‘\Magento\Catalog\Model\Product’);
$product->setSku(‘mysku’); // 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->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product
$product->setTaxClassId(0); // Tax class id
$product->setTypeId(‘simple’); // type of product
$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 custom options to the product this can be applied for other product type such as Configurable Product, Virtual, Downloadable Product, etc.

// Adding Custom option to product
$options = array(
array(
“sort_order”    => 1,
“title”         => “Custom Option 1”,
“price_type”    => “fixed”,
“price”         => “1000”,
“type”          => “field”,
“is_require”   => 0
),
array(
“sort_order”    => 2,
“title”         => “Custom Option 2”,
“price_type”    => “fixed”,
“price”         => “2000”,
“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);
}

To create simple, configurable, downloadable products as the following:
•    Simple product: you need to pass the weight setting.
•    Configurable product: it is required to combine between associated products current product.
•    Downloadable product: it is required to insert the download link into the current product.

$productId = 1; // 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(13, 15); // Super Attribute Ids Used To Create Configurable Product
$associatedProductIds = array(2,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();

Simple Product with custom attributes:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create(‘\Magento\Catalog\Model\Product’);
$product->setSku(‘sku’); // Set your sku here
$product->setName(‘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();

// Adding Image to product
$imagePath = “simple.jpg”; // path of the image
$product->addImageToMediaGallery($imagePath, array(‘image’, ‘small_image’, ‘thumbnail’), false, false);
$product->save();

// Adding Custom option to product
$options = array(
array(
“sort_order”    => 1,
“title”         => “Custom Option 1”,
“price_type”    => “fixed”,
“price”         => “1000”,
“type”          => “field”,
“is_require”   => 0
),
array(
“sort_order”    => 2,
“title”         => “Custom Option 2”,
“price_type”    => “fixed”,
“price”         => “2000”,
“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);
}

Create a configurable Magento 2 product:

$configurable_product = $this->_objectManager->create(‘\Magento\Catalog\Model\Product’);
$configurable_product->setSku(‘testconfigurable’);
$configurable_product->setName(‘test configurable name’);
$configurable_product->setAttributeSetId(4);
$configurable_product->setStatus(1);
$configurable_product->setTypeId(‘configurable’);
$configurable_product->setPrice(110);
$configurable_product->setWebsiteIds(array(1));
$configurable_product->setCategoryIds(array(31));
$configurable_product->setStockData(array(
‘use_config_manage_stock’ => 0, //’Use config settings’ checkbox
‘manage_stock’ => 1, //manage stock
‘is_in_stock’ => 1, //Stock Availability
)
);

$configurable_product->getTypeInstance()->setUsedProductAttributeIds(array(152),$configurable_product); //attribute ID of attribute ‘size_general’ in my store
$configurableAttributesData = $configurable_product->getTypeInstance()->getConfigurableAttributesAsArray($configurable_product);
$configurable_product->setCanSaveConfigurableAttributes(true);
$configurable_product->setConfigurableAttributesData($configurableAttributesData);
$configurableProductsData = array();
$configurableProductsData[$simple_product_id] = array( //[$simple_product_id] = id of a simple product associated with this configurable
‘0’ => array(
‘label’ => ‘S’, //attribute label
‘attribute_id’ => ‘152’, //attribute ID of attribute ‘size_general’ in my store
‘value_index’ => ‘193’, //value of ‘S’ index of the attribute ‘size_general’
‘is_percent’    => 0,
‘pricing_value’ => ‘100’,
)
);
$configurable_product->setConfigurableProductsData($configurableProductsData);
$configurable_product->save();
echo “conf product id: “.$configurable_product->getId().”\n”;

Also Read :   What is the features of SEO Pack and roles of security – WordPress
X
Subscribe to our newsletter
Subscribe to our newsletter today to receive updates on the latest news and offers.
100% Privacy. No spam guaranteed
webe tutorial
Menu