{"id":846,"date":"2020-02-26T00:57:47","date_gmt":"2020-02-26T00:57:47","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/2020\/02\/26\/programmatically-create-virtual-product-in-magento-2\/"},"modified":"2025-05-22T14:55:22","modified_gmt":"2025-05-22T09:25:22","slug":"programmatically-create-virtual-product-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/programmatically-create-virtual-product-in-magento-2\/","title":{"rendered":"Simplest Way To Programmatically Create Virtual Product In Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/experienceleague.adobe.com\/en\/docs\/commerce-admin\/catalog\/products\/types\/product-create-virtual\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2 Virtual Products<\/a>&nbsp;are the non-tangible products that can\u2019t be touched and have no weight.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are&nbsp;<a href=\"https:\/\/experienceleague.adobe.com\/en\/docs\/commerce-admin\/catalog\/products\/product-create\" target=\"_blank\" rel=\"noreferrer noopener\">six product types<\/a>&nbsp;in Magento 2:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Simple Product<\/li>\n\n\n\n<li>Configurable Product<\/li>\n\n\n\n<li>Grouped Product<\/li>\n\n\n\n<li>Virtual Product<\/li>\n\n\n\n<li>Bundle Product<\/li>\n\n\n\n<li>Downloadable Product<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The virtual products are products such as memberships, services, warranties, subscriptions, or any type of digital file. They are sold either individually or with grouped or bundle products. The perfect example of a virtual product is an ebook or a gym membership.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s the easy method to&nbsp;<em><strong>programmatically create virtual product in Magento 2<\/strong><\/em>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Method to programmatically create virtual product in Magento 2:<\/h2>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\nuse Magento\\Framework\\App\\Bootstrap;\ninclude('app\/bootstrap.php');\n$bootstrap = Bootstrap::create(BP, $_SERVER);\n$objectManager = $bootstrap->getObjectManager();\n$state = $objectManager->get('Magento\\Framework\\App\\State');\n$state->setAreaCode('frontend');\n$objectManager = Magento\\Framework\\App\\ObjectManager::getInstance(); \/\/ instance of object manager\ntry {\n    $product = $objectManager->create('Magento\\Catalog\\Model\\Product');\n    $product->setSku('Main Virtual'); \/\/ Set your sku here\n    $product->setName('Virtual Color Product'); \/\/ Name of Product\n    $product->setAttributeSetId(4); \/\/ Attribute set id\n    $product->setStatus(1); \/\/ Status on product enabled\/ disabled 1\/0\n    $product->setWeight(10); \/\/ weight of product\n    $product->setVisibility(4); \/\/ visibilty of product (catalog \/ search \/ catalog, search \/ Not visible individually)\n    $product->setTaxClassId(0); \/\/ Tax class id\n    $product->setTypeId('virtual'); \/\/ type of product (simple\/virtual\/downloadable\/configurable)\n    $product->setPrice(500); \/\/ price of product\n    $product->setStockData(\n        array(\n            'use_config_manage_stock' => 0,\n            'manage_stock' => 1,\n            'is_in_stock' => 1,\n            'qty' => 200\n        )\n    );\n\/\/ Adding Image to product\n    $mediaDir = $objectManager->get('Magento\\Framework\\App\\Filesystem\\DirectoryList')->getPath('media');\n    $imagePath = \"logo.jpg\"; \/\/ path of the image\n    $imageFilename = basename($imagePath);\n    $image_type = substr(strrchr($imageFilename,\".\"),1);\n    $filename = md5($imagePath . strtotime('now')).'.'.$image_type;\n    if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true);\n    else chmod($mediaDir, 0777);\n    $filepath = $mediaDir . '\/catalog\/product'. $filename; \/\/path for temp storage folder: pub\/media\n    file_put_contents($filepath, file_get_contents(trim($imagePath)));\n    $imgArray  = $filepath;\n    $product->addImageToMediaGallery($imgArray, array('image', 'small_image', 'thumbnail'), false, false);\n    $product->save();\n\/\/ Adding Custom option to product\n    $options = array(\n        array(\n            \"sort_order\" => 1,\n            \"title\" => \"Custom Option 1\",\n            \"price_type\" => \"fixed\",\n            \"price\" => \"10\",\n            \"type\" => \"field\",\n            \"is_require\" => 0\n        ),\n        array(\n            \"sort_order\" => 2,\n            \"title\" => \"Custom Option 2\",\n            \"price_type\" => \"fixed\",\n            \"price\" => \"20\",\n            \"type\" => \"field\",\n            \"is_require\" => 0\n        )\n    );\n    foreach ($options as $arrayOption) {\n        $product->setHasOptions(1);\n        $product->getResource()->save($product);\n        $option = $objectManager->create('\\Magento\\Catalog\\Model\\Product\\Option')\n            ->setProductId($product->getId())\n            ->setStoreId($product->getStoreId())\n            ->addData($arrayOption);\n        $option->save();\n        $product->addOption($option);\n    }\n}\ncatch (\\Exception $e){\n    echo $e->getMessage();\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That\u2019s it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Please share this post with the Magento community via social media profiles.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Magento 2 Virtual Products&nbsp;are the non-tangible products that can\u2019t be touched and have no weight. There are&nbsp;six product types&nbsp;in Magento 2: The virtual products are&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-846","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/846","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=846"}],"version-history":[{"count":3,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/846\/revisions"}],"predecessor-version":[{"id":15066,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/846\/revisions\/15066"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=846"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=846"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=846"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}