How To Delete Cart Price Rules By ID In Magento 2

Cart price rules apply discounts to items in the cart, based on a set of conditions.

We’ve already discussed the steps to add Magento 2 cart price rules earlier.

Now, you may have the business requirement to delete cart price rules based on the season, offer validity, etc. It may even happen that the discount is to be canceled due to some legit rule violation or any other reason.

One of the ways to do so is to delete cart price rules by ID in Magento 2 store as shown below.

Method To Delete Cart Price Rules by ID In Magento 2:

use Magento\SalesRule\Api\RuleRepositoryInterface;
use Exception;

protected $ruleRepository;

public function __construct(RuleRepositoryInterface $ruleRepository) {
    $this->ruleRepository = $ruleRepository;
}


//need to pass rule id
public function deleteById($ruleId)
{
    try {
        $salesRule = $this->ruleRepository->deleteById($ruleId);
    } catch (Exception $e) {
        \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info($e->getMessage());
    }
}

That’s it.

Follow the above method to remove the discount price rules programmatically by ID in Magento 2.

Removing the applied cart rules avoids mistakes in discount and incur any loss!

Please share the post via social media for fellow Magento developers to make their tasks easier.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...