Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save magemore/f4ff3c22ec8f29106a5ea1619e430b2c to your computer and use it in GitHub Desktop.
Save magemore/f4ff3c22ec8f29106a5ea1619e430b2c to your computer and use it in GitHub Desktop.
magento 2 create product programmatically
<?php
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$_product = $objectManager->create('Magento\Catalog\Model\Product');
$_product->setName('Test Product');
$_product->setTypeId('simple');
$_product->setAttributeSetId(4);
$_product->setSku('test-SKU');
$_product->setWebsiteIds(array(1));
$_product->setVisibility(4);
$_product->setPrice(array(1));
$_product->setImage('/testimg/test.jpg');
$_product->setSmallImage('/testimg/test.jpg');
$_product->setThumbnail('/testimg/test.jpg');
$_product->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 100 //qty
)
);
@pawanocodewire
Copy link

I use this code But Images are not displaying , Even Gave the absolute path of images.

Any Solution for the Images ?

@kumarA8
Copy link

kumarA8 commented Mar 28, 2018

Dont you think you need to save this too ?
$_product->save()

@lucasvm
Copy link

lucasvm commented Apr 25, 2018

When using this code im getting:
URL key for specified store already exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment