How To Add Or Create Magento 2 Virtual Product Programmatically

How can I add or create a virtual product for my Magento 2 store programmatically

You need to use Magento\Catalog\Api\Data\ProductInterfaceFactory and \Magento\Catalog\Api\ProductRepositoryInterface  to create a virtual product programmatically.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productFactory = $objectManager->get('Magento\Catalog\Api\Data\ProductInterfaceFactory');

$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');

$_product = $productFactory->create();

$_product->setSku('product');

$_product->setName('Product');

$_product->setDescription('Product Description');

$_product->setShortDescription('Product Short Description');

$_product->setWebsiteIds([1]);

$_product->setCategoryIds(["1","2"]);

$_product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL);

$_product->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);

$_product->setPrice(array(1));

$_product->setAttributeSetId(4);

$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);

$product->setUrlKey("test");


$_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
        )
    );

$product = $productRepository->save($product);

$imagePath = '/product/product.jpg'; 

$product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);

$product->save();

Leave a Reply

avatar
  Subscribe  
Notify of