Magento 2 creating virtual product progamatically

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();
    }

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!