- Create di.xml file in the etc/frontend folder.
- Create the Product.php class in the “Magestore\Training\Plugin” folder
- The $result is the result after run the original method getPrice()
As you know, when we create the extension in Magento, we usually change or modify something in the Magento work flow. What if I guide you through another solution that can use Plugin to change the Magento 2 Product Price?
As normally, we can use the “Event – Observer” to make it. However, in some cases, it doesn’t have “Event” so we must use the “Rewrite” to make the modify. The rewrite will cause the conflict with other module because two modules can not rewrite at the same file. In the Magento 2, it has the “Plugin” so we can reduce the conflict than using the rewrite.
Magento enables you to change, or extend, the behavior of any original, public method in any Magento class. It has some limitations:
- Final methods / classes
- Non-public methods
- Class methods (such as static methods)
- Virtual types
In this tutorial, I will show you how to use the plugin to custom the product price of Magento 2.
Please create the “di.xml” in the scope which you want to use the plugin. In this tutorial, I will place it in the frontend area, so you can create di.xml file in the etc/frontend folder.
<plugin name="change_product" type=" Magestore\Training\Plugin\Product " sortOrder="1" disabled="true"/>
- Please create the Product.php class in the “Magestore\Training\Plugin” folder. To change the product price, we will change the values returned by an original method or add some behavior after an original method is called, so we will use the “after” prefix.
- The $result is the result after run the original method getPrice(). In this example, I will change the price of the product by multiply it with 2.
public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result)
After that, please go to frontend and check the product price is changed or not. If any problems occurs, you can find more of our expert’s advises & tutorials here.
Thank you for reading !
Your Magento website needs a powerful Magento ERP for stock control.
DON'T MISS THE CHANCE!