:::: MENU ::::

magento 2 create virtual product programmatically

Recent QuestionsCategory: Magento 2 Questionsmagento 2 create virtual product programmatically
Raja Usman asked 2 weeks ago

I’m using magento v2.5.5 to develop an extension, in this extension i have to generate virtual product with non manageble stock (infinite stock), how to do this programmatically.

1 Answers
Best Answer
qaisarsatti Staff answered 2 weeks ago

For creating virtual product progamatically use below code and you want to use unlimited quantity just use ‘manage_stock’ => 0,

protected $_product;  


  public function __construct(

        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {


        $this->_productloader = $_productloader;

    }
    public function createProduct()
    {

        $_product = $this->_productloader->create();
        $_product->setName('First Test Product');
        $_product->setTypeId('virtual');
        $_product->setAttributeSetId(4);
        $_product->setSku('test-SKU');
        $_product->setWebsiteIds(array(1));
        $_product->setVisibility(4);
        $_product->setPrice(400);
        $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 0, //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' => 1000 //qty
            )
        );

        $_product->save();
        echo $_product->getId();
    }