Hello Friends!
In this blog, we are going to learn how we can override a product’s special price on the category product page and product page.
To override the special price of a product, please follow the below steps:
1. Declare the plugin: First of all, we will declare the plugin in di.xml file inside app/code/Vendor/CustomModule/etc/ directory.
<?xml version="1.0"?> <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="change_product_price" type="Vendor\CustomModule\Plugin\Catalog\Model\Product" sortOrder="1" disabled="false"/> </type> </config>
2. Define the plugin: To override the special price, we will create the ‘after method plugin’ for getSpecialPrice method of \Magento\Catalog\Model\Product class. Here, we have created the Product.php plugin file inside app/code/Vendor/CustomModule/Plugin/Catalog/Model/ directory.
<?php /** * Vendor Desc. * php version 7.3.* * * @category Vendor * @package Vendor_CustomModule * @author Vendor * @copyright Vendor (https://example.com) * @license https://example.com/license.html */ namespace Vendor\CustomModule\Plugin\Catalog\Model; class Product { /** * Get product's special price * * @param \Magento\Catalog\Model\Product $subject * @param float $result * * @return float */ public function afterGetSpecialPrice( \Magento\Catalog\Model\Product $subject, $result ) { return 30; //special must be less than product price otherwise it will display the product price } }
3. See the result: Now, we can see the result in the following images. Here, we have created a product with the price $45 and its special price is $40. But after overriding the special price, it will be displayed $30 on the category product page and product details page.
Hope this will be helpful. Thanks 🙂
Previous Blog: Detect your device is Mobile or Desktop in Magento 2
Next Blog: Override Product Tier Prices in Magento 2
Be the first to comment.