Skip to content

Instantly share code, notes, and snippets.

@Alexander-Pop
Last active April 23, 2025 21:13
Show Gist options
  • Save Alexander-Pop/ca3540cb32e8c8e80575b163cb6ed7fe to your computer and use it in GitHub Desktop.
Save Alexander-Pop/ca3540cb32e8c8e80575b163cb6ed7fe to your computer and use it in GitHub Desktop.
Magento 2 - Bulk delete cart rules
<?php
namespace MyVendor\MyExtension\Helper;
use Magento\SalesRule\Api\RuleRepositoryInterface;
class RuleDeleter
{
private $ruleRepository;
public function __construct(
RuleRepositoryInterface $ruleRepository
) {
$this->ruleRepository = $ruleRepository;
}
public function deleteRules(array $ruleIds)
{
foreach ($ruleIds as $ruleId) {
try {
$rule = $this->ruleRepository->getById($ruleId);
if($rule && $rule->getIsActive() == 0) {
$this->ruleRepository->deleteById($ruleId);
echo "Deleted inactive rule '" . $rule->getName() . "' with ID: " . $ruleId . "\n";
}
} catch (\Exception $e) {
// Handle exceptions, show error
echo "Error deleting rule with ID: " . $ruleId . ". Error: " . $e->getMessage();
}
}
}
}
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);
use Magento\Framework\App\Bootstrap;
require '../app/bootstrap.php';
$scriptCustom = new scriptCustom();
$scriptCustom->run();
class scriptCustom
{
const RULES_TO_DELETE = [82,83];
protected \Magento\Framework\ObjectManagerInterface $objectManager;
protected mixed $ruleRepository;
public function __construct()
{
$bootstrap = Bootstrap::create(BP, $_SERVER);
$this->objectManager = $bootstrap->getObjectManager();
$this->ruleRepository = $this->objectManager->get('Magento\SalesRule\Api\RuleRepositoryInterface');
$state = $this->objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('crontab');
}
public function run(): void
{
$ruleIds = self::RULES_TO_DELETE;
echo "Start running ... \n";
foreach ($ruleIds as $ruleId) {
try {
// Load the rule by ID
$rule = $this->ruleRepository->getById($ruleId);
if($rule && $rule->getIsActive() == 0) {
$this->ruleRepository->deleteById($ruleId);
echo "Deleted inactive rule '" . $rule->getName() . "' with ID: " . $ruleId . "\n";
}
} catch (\Exception $e) {
// Handle exceptions - show log the error
echo "Error deleting rule with ID: " . $ruleId . ". Error: " . $e->getMessage() . "\n";
}
}
echo "Finish running ... \n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment