Planning to enhance user experience with virtual products like memberships, subscriptions, services, warranties and digital downloads? Well, here is a full-fledged guide to creating virtual products programmatically on your online store. Now, develop all the types of virtual products on Magento 2 store on your own. The virtual product created this way can be sold individually or can be grouped and product bundle type.
In order to create a virtual product, we must first create a script.Â
Create virtual.php file at your Magento’s root folder and this below code :
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product = $objectManager->create('Magento\Catalog\Model\Product');
try {
$product->setName('Virtual Product'); // Set Product Name
$product->setTypeId('virtual'); // Set Product // Set SKU Type Id
$product->setAttributeSetId(4); // Set Attribute Set ID
$product->setSku('virtual-product'); // Set SKU
$product->setWebsiteIds([1]); // Set Website Ids
$product->setVisibility(4); // Set Visibility
$product->setPrice(100); // Set Price
$product->setImage('/virtual/test.jpg'); // Image Path
$product->setSmallImage('/virtual/test.jpg'); // Small Image Path
$product->setThumbnail('/virtual/test.jpg'); // Thumbnail Image Path
$product->setStockData(
[
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'min_sale_qty' => 1,
'max_sale_qty' => 2,
'is_in_stock' => 1,
'qty' => 100,
]
);
$product->save();
if ($product->getId()) {
echo "Product Created Successfully";
}
} catch (\Exception $e) {
echo $e->getMessage();
}
That’s it !!
In addition to this, you can also set static details based on your requirements. For instance, if you are looking for ways to create multiple products using a script, simply use the same script and customize code for multiple products.
Now, execute this file on the front-end side :Â {baseUrl}/virtual.php
Build a loyal and returning customer base with incredible virtual products on the ecommerce store. For any kind of assistance, reach us out today! Our Magento 2 experts will help you with the best possible solution.



