This article will help you to create cart rule programatically with shopping cart amount or any other condition. Here I am giving you an example that how you can create cart rule with cart amount condition.
Code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$sp_storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$website_id = $sp_storeManager->getStore()->getWebsiteId();
$simple_action = 'by_percent'; //or $simple_action = 'by_fixed';
$free_shipping = '1'; //or $free_shipping = '0';
$sp_customerGroup = $objectManager->create('\Magento\Customer\Model\ResourceModel\Group\Collection');
$customerGroups = $sp_customerGroup->toOptionHash();
foreach (array_keys($customerGroups) as $key) {
$customerGroup[] = $key;
}$model = $objectManager->create(‘Magento\SalesRule\Model\Rule’);
$data['name'] = "5% off over 500";
$data['coupon_code'] = '5OFF500';
$data['discount_amount'] = '5';
$data['description'] = 'User will get 5% off on purchase of 500 or more';
$data['from_date'] = '2019-5-20';
$data['to_date'] = '2019-5-26;
$data['simple_action'] = '';
$data['coupon_type'] = '2';
$data['website_ids'] = array($website_id);
$data['customer_group_ids'] = $customer_groups;
$data['is_active'] = '1';
$data['use_auto_generation'] = '0';
$data['uses_per_customer'] = '1';
$data['uses_per_coupon'] = '1';
$data['is_advanced'] = '1';
$data['sort_order'] = '1';
$data['discount_qty'] = '0';
$data['simple_free_shipping'] = $free_shipping;
$data['is_rss'] = '0';
$data['apply_to_shipping'] = '0';
$data['times_used'] = '0';
$data['conditions']['1'] = array('type' => 'Magento\SalesRule\Model\Rule\Condition\Combine','aggregator' => 'all','value' => '1','new_child' => '');
$data['conditions']['1--1'] = array('type' => 'Magento\SalesRule\Model\Rule\Condition\Address','attribute' => 'base_subtotal','operator' => '>=','value' => $min_cart_amount);
$model->loadPost($data);
$model->save();
$model->save();
Thank you and enjoy your coding!
Leave a Reply