In this blog, we will describe how to programmatically create Magento 2’s simple product using a PHP file in the root directory. Firstly we need to create a PHP file createsimpleproduct.php and add the code given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
<?php use Magento\Framework\AppInterface; try { require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try{ $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('Magento\Framework\App\State'); $appState->setAreaCode('frontend'); $product = $objectManager->create('Magento\Catalog\Model\Product'); $sku = 'wt-1001'; // set your sku $product->setSku($sku); $product->setName('Plain Burgundy Women Full Sleeves T-shirt'); // set your Product Name of Product $product->setMetaTitle('Plain Burgundy Women Full Sleeves T-shirt'); $product->setMetaKeyword('Plain Burgundy Women Full Sleeves T-shirt'); $product->setMetaDescription('Plain Burgundy Women Full Sleeves T-shirt'); $product->setDescription('Plain Burgundy Women Full Sleeves T-shirt'); $product->setAttributeSetId(4); // set attribute id $product->setStatus(1); // status enabled/disabled 1/0 $product->setWeight(1); // set weight of product $product->setVisibility(4); // visibility of product (Not Visible Individually (1) / Catalog (2)/ Search (3)/ Catalog, Search(4)) $product->setWebsiteIds(array(1)); $product->setTaxClassId(0); // Tax class ID $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable) $product->setPrice(425); // set price of product $product->setStockData( array( 'use_config_manage_stock' => 0, 'manage_stock' => 1, 'is_in_stock' => 1, 'qty' => 100 ) ); $product->save(); $categoryIds = array('2','3'); // assign your product to category using Category Id $category = $objectManager->get('Magento\Catalog\Api\CategoryLinkManagementInterface'); $category->assignProductToCategories($sku, $categoryIds); echo "$sku Product Created Successfully "; } catch(\Exception $e){ print_r($e->getMessage()); } After creating this php file you can see the result after run this given url for creating a simple product. https://yourdomain.com/createsimpleproduct.php |
Thank You!
Hit 5 Stars if you find this post helpful
0 (based on 0 Reviews)