在 Magento 2 中以编程方式创建简单产品

redmaomail 2024-07-24 18:24 阅读数 62 #Magento

红帽云邮外贸主机

在 Magento 2 中以编程方式创建简单产品的步骤:

第 1 步:首先,在 Magento 根目录中创建一个simple_product.php文件并添加以下给定代码。

<?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 = 'your_sku';  // set your sku

$product->setSku($sku);

$product->setName('Simple Product Name'); // set your Product Name of Product

$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(100); // 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());

}


第 2 步:完成上述步骤后,您需要运行下面给出的 URL 来创建一个简单的产品。

https://yourdomain.com/simple_product.php


红帽云邮外贸主机

分享到:
版权声明:本站内容源自互联网,如有内容侵犯了你的权益,请联系删除相关内容。
    红帽云邮外贸主机
热门
    红帽云邮外贸主机
    红帽云邮外贸主机