Magento 2 Remove Product Attribute Programmatically

If you want to remove product attribute programmatically then you are in a right place. In this article I am going to explain how to remove product attribute programmatically in Magento 2.

First of all you need to create one module. If you already have a module then go with that but don't forget to change the setup version and if you are new in Magento then check our another article How To Create a Magento 2 Module.

Let's get started!!

Now I assume you already have magento module.

To Remove the product attribute programmatically in module we need to create InstallData class in our Magento 2 Extension

Let's Create InstallData.php file at app/code/Devhooks/HelloWorld/Setup/InstallData.php and paste the below code.

<?php namespace Devhooks\HelloWorld\Setup; use Magento\Eav\Setup\EavSetup; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; class InstallData implements InstallDataInterface { private $eavSetupFactory; public function __construct(EavSetupFactory $eavSetupFactory) { $this->eavSetupFactory = $eavSetupFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->removeAttribute( \Magento\Catalog\Model\Product::ENTITY, 'custom_attribute'); } }

In above code we have remove a text type attribute. Replace, custom_attribute with your attribute code.

Now, open Command line in folder root of magento and run both commands for remove product attribute programmatically.

php bin/magento setup:upgrade php bin/magento cache:flush php bin/magento indexer:reindex

Bingo!! we are done, now go to the Admin > Store > Attributes > Product and find your attribute is exist or not.

That's it!!

If you want to add new product attribute programmatically then check our another article Magento 2 Add Product Attribute Programmatically

I hope this article helped you to find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other questions on that.

P.S. Do share this article with your team.

Recent Articles
Chrome Extension
Copyright © 2024 All rights reserved.
Ads OFF toggle_off