Giving Individual Percentage Discounts for Products in Magento
Offering discounts on specific products is an essential feature for many e-commerce stores. However, Magento’s core functionality doesn’t directly support assigning percentage discounts to individual items. In this post, we’ll guide you through the process of creating a custom discount extension that applies a percentage reduction to particular simple products.
Understanding the Requirement
You want to give a percentage discount on specific simple products in your Magento store and display the discounted price on the frontend. The built-in shipping cart rules aren’t suitable as they apply to the entire cart, not individual items. Assigning special prices isn’t ideal either since it doesn’t support percentage values.
Building the Custom Extension
To achieve this, we’ll create a custom module that:
- Adds a new field for the discount percentage in the product edit page.
- Calculates and stores the discounted price when saving the product.
- Displays the special price instead of the regular price on the frontend.
Here’s an overview of the steps involved:
Step 1: Create the Module Structure
Create a new folder under app/code/VendoreName/ModuleName. The module name could be something like Vendor_PercentageDiscount.
- app
-- code
-- VendoreName
-- ModuleName
- Setup.php
- registration.php
- etc
-- module.xml
- etc
-- config.xml
- Controller
-- IndexController.php
- Observer
-- SaveAfterObserver.php
Step 2: Configuring the Module
In registration.php, define your module’s dependencies:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor_ModuleName',
__DIR__
);
The module.xml file should contain the following configuration:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<modules>
<Vendor_ModuleName>
<active>true</active>
<codePool>main</codePool>
</Vendor_ModuleName>
</modules>
</config>
Step 3: Adding the Discount Field to Product Edit Page
To add a new field for the discount percentage, create an etc/adminhtml/di.xml file:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Model\Product">
<plugin name="Vendor_ModuleName_model_product_plugin"
type="Vendor\ModuleName\Plugin\Product"
sortOrder="10"/>
</type>
</config>
In your Plugin/Product.php file, you can use the following code to add a new field for discount percentage:
public function afterGetData(\Magento\Catalog\Model\Product $subject)
{
return array_merge($subject->getData(), [
'percentage_discount' => $subject->getPercentageDiscount()
]);
}
Step 4: Saving the Discounted Price
Create a new observer Vendor/ModuleName/Observer/SaveAfterObserver.php that listens to the catalog_product_save_after event. In this observer, calculate and save the discounted price:
public function execute(\Magento\Framework\Event\Observer $observer)
{
$product = $observer->getProduct();
if ($product->getPercentageDiscount()) {
$regularPrice = $product->getPrice();
$discountedPrice = $regularPrice * ((100 - $product->getPercentageDiscount()) / 100);
$product->setSpecialPrice($discountedPrice);
}
}
Don’t forget to define the observer in your etc/adminhtml/di.xml file:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<event name="catalog_product_save_after">
<observer name="Vendor_ModuleName_catalog_product_save_after" instance="Vendor\ModuleName\Observer\SaveAfterObserver"/>
</event>
</config>
Step 5: Displaying the Discounted Price
To display the special price on the frontend, you can use a custom theme or override the catalog/product/view.phtml template. In your theme layout XML, set the template to your custom version:
<referenceBlock name="product.info.price">
<action method="setTemplate">
<argument name="template" xsi:type="string">Vendor_ModuleName::product/view/price.phtml</argument>
</action>
</referenceBlock>
In your price.phtml template, you can display the regular price and the special price conditionally:
<?php if ($block->displayRegularPrice()): ?>
<div class="price-box">
<span class="regular-price" id="product-price-<?= /* @noEscape */ $product->getId() ?>">
<?= /* @escapeNotVerified */ $block->formatCurrency($product->getFinalPrice()) ?>
</span>
</div>
<?php endif; ?>
<?php if ($block->displaySpecialPrice()): ?>
<script type="text/javascript">
require(['jquery'], function ($) {
$('#product-price-<?= /* @noEscape */ $product->getId() ?>').html("<?= /* @escapeNotVerified */ $block->formatCurrency($product->getFinalPrice()) ?>");
});
</script>
<?php endif; ?>
Conclusion
Creating a custom module to handle percentage discounts for individual products in Magento requires some development effort but allows you to maintain full control over the discount logic. By following this guide, you can create an extension that meets your specific business requirements while keeping your codebase clean and maintainable.
Remember to test your extension thoroughly before deploying it to a production environment. If you need further assistance or want to explore more advanced features like tiered pricingdiscounts, feel free to reach out to the experienced development team at Laravel Company.
Happy coding!