How to create virtual product in Magento 2 programmatically ?

Welcome to Kishan Savaliya's Magento 2 Blog.In this blog post, I will explain how to create a virtual product in Magento 2 programmatically. We can create virtual product using backend too but in some case if you need to create virtual products again and again then if you will create product from backend then it will take more time and instead of that you can do that easily with simple root script file, it will save your time and that is quite easy to do.

Virtual products, or digital goods, represent non-tangible items such as memberships, services, warranties, or subscriptions and digital downloads of books, music, videos, or other products. Virtual products can be sold individually or included as part of the Grouped Product or Bundle Product product types.

Virtual products are much like simple products, but it does not have weight.

Shipping options do not appear during checkout unless there is a real product in the cart.

So let's start.. Move into your Magento 2 root directory and create below file there..


Content for this file is..

require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$product = $objectManager->create(Magento\Catalog\Model\Product::class);

try {
    $product->setAttributeSetId(4); //Set your attribute set ID, I used 4 because I have default Luma theme and I want to use Default attribute set and it's attribute ID is 4, find your ID and set here.
    $product->setName('Virtual Product name');
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'min_sale_qty' => 1,
            'max_sale_qty' => 10,
            'is_in_stock' => 1,
            'qty' => 50
    $product->setDescription('<p>Virtual Product Description</p>');
    $product->setShortDescription('<p>Virtual Product Short Description</p>');
    $product->setWebsiteIds([1]); //Find your website ID and set that ID instead of 1 in array
    $product->setVisibility(4); //To display virtual product in frontend you can set visibility to catalog, search

        echo "Virtual Product created successfully.";
} catch (\Exception $e) {
    echo $e->getMessage();

You can change above content based on your requiremrent. You can simply run below URL in browser it'll create virtual product in your Magento.


That's it.

Hope you may like this article and can understand this easily. You can add comments below in case if you have any questions regarding this article or if I missed anything here. I will check and get back to you with proper solution.

If you enjoyed this blog post, share it with friends!