Offering discounts is a great way to attract more customers and grab the attention of your previous clients. Not only that, but it helps spike the number of sales and improves the reputation of your business as well. In short, discounts can bring unprecedented success to your store!
Hence, we’re going to learn how to add custom discount in Magento 2 in this tutorial. While you can add custom discounts to your Magento 2 stores by editing core files, it may not be the best way to do it. A better way to do it is by using a custom module.
Create A Module
Namespace
Go to app in the root directory of Magento 2 and create directories app/code/Cloudways.
Module
Go to app/code/Cloudways and create the directory Mymodule.
Declare Module
Go to the root directory of module app/code/Cloudways/Mymodule and create directory etc. Create module.xml in app/code/Cloudways/etc and paste the following code in the file.
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Cloudways_Mymodule" setup_version="1.0.0"></module> </config>
New Customer? Claim Your 30% Off Cloudways Promo Code
Welcome to Cloudways, where your website finds the perfect hosting solution. Claim your promo code and get 30% off for 3 months on all plans!
Register Module
Go to root directory of module app/code/Cloudways/Mymodule and create registration.php. Paste the following code in it.
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Cloudways_Mymodule', __DIR__ );
Now run the following command to check the status of Modules:
php bin/magento module:status
If you find your module Cloudways_Mymodule disabled, then run the following command:
php bin/magento module:enable Cloudways_Mymodule
Now just upgrade your module.
php bin/magento setup:upgrade
Register Discount
After the creation of module, now go to app/code/Cloudways/Mymodule/etc and create sales.xml. Paste the following code in the file:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd"> <section name="quote"> <group name="totals"> <item name="testdiscount" instance="Cloudways\Mymodule\Model\Quote\Discount" sort_order="500"/> </group> </section> </config>
Looking for a Fast and Hassle Free Magento Hosting Experience?
Cloudways offers a fast, cost-effective, and easy-to-manage Magento 2 hosting solution that you can deploy on top 3 infrastructure that includes DigitalOcean, AWS, and Google Cloud.
Add Custom Discount
First, create directories Model/Quote in app/code/Cloudways/Mymodule. In this tutorial, we will set a 10 percent discount on the Total Amount. Now create Discount.php in app/code/Cloudways/Model/Quote and paste the following code in the file:
<?php namespace Cloudways\Mymodule\Model\Quote; class Discount extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal { public function __construct( \Magento\Framework\Event\ManagerInterface $eventManager, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\SalesRule\Model\Validator $validator, \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency ) { $this->setCode('testdiscount'); $this->eventManager = $eventManager; $this->calculator = $validator; $this->storeManager = $storeManager; $this->priceCurrency = $priceCurrency; } public function collect( \Magento\Quote\Model\Quote $quote, \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment, \Magento\Quote\Model\Quote\Address\Total $total ) { parent::collect($quote, $shippingAssignment, $total); $address = $shippingAssignment->getShipping()->getAddress(); $label = 'My Custom Discount'; $TotalAmount=$total->getSubtotal(); $TotalAmount=$TotalAmount/10; //Set 10% discount $discountAmount ="-".$TotalAmount; $appliedCartDiscount = 0; if($total->getDiscountDescription()) { $appliedCartDiscount = $total->getDiscountAmount(); $discountAmount = $total->getDiscountAmount()+$discountAmount; $label = $total->getDiscountDescription().', '.$label; } $total->setDiscountDescription($label); $total->setDiscountAmount($discountAmount); $total->setBaseDiscountAmount($discountAmount); $total->setSubtotalWithDiscount($total->getSubtotal() + $discountAmount); $total->setBaseSubtotalWithDiscount($total->getBaseSubtotal() + $discountAmount); if(isset($appliedCartDiscount)) { $total->addTotalAmount($this->getCode(), $discountAmount - $appliedCartDiscount); $total->addBaseTotalAmount($this->getCode(), $discountAmount - $appliedCartDiscount); } else { $total->addTotalAmount($this->getCode(), $discountAmount); $total->addBaseTotalAmount($this->getCode(), $discountAmount); } return $this; } public function fetch(\Magento\Quote\Model\Quote $quote, \Magento\Quote\Model\Quote\Address\Total $total) { $result = null; $amount = $total->getDiscountAmount(); if ($amount != 0) { $description = $total->getDiscountDescription(); $result = [ 'code' => $this->getCode(), 'title' => strlen($description) ? __('Discount (%1)', $description) : __('Discount'), 'value' => $amount ]; } return $result; } }
Create Layout Files
Go to app/code/Cloudways/Mymodule and create directories view/frontend/layout.
Create checkout_cart_index.xml in app/code/Cloudways/Mymodule/view/frontend/layout. Paste the following code in the file:
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.cart.totals"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="block-totals" xsi:type="array"> <item name="children" xsi:type="array"> <item name="before_grandtotal" xsi:type="array"> <item name="children" xsi:type="array"> <item name="testdiscount" xsi:type="array"> <item name="config" xsi:type="array"> <item name="title" xsi:type="string" translate="true">My Discount </item> </item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
Create checkout_index_index.xml in app/code/Cloudways/Mymodule/view/frontend/layout. Paste the following code in the file:
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.root"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="checkout" xsi:type="array"> <item name="children" xsi:type="array"> <item name="sidebar" xsi:type="array"> <item name="children" xsi:type="array"> <item name="summary" xsi:type="array"> <item name="children" xsi:type="array"> <item name="totals" xsi:type="array"> <item name="children" xsi:type="array"> <item name="testdiscount" xsi:type="array"> <item name="config" xsi:type="array"> <item name="title" xsi:type="string" translate="true">My Discount </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
Now, just go to the checkout page and you will see the result.
Final Words
After following this tutorial, you should be able to add custom discount in Magento 2. Just remember that adding discounts can help you increase your sales by a huge margin, so it would be wise to do so. If you have any problem or would like to add to the discussion, leave a comment below!
Abdur Rahman
Abdur Rahman is the Magento whizz at Cloudways. He is growth ambitious, and aims to learn & share information about Ecommerce & Magento Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]