Shopping cart

How to change product price with Plugin in Magento 2

Using a plugin to change the product price in Magento 2 is one of the great alternative choices when you start with Magento 2 store, and have a tendency to change something like product price. As normally, there are many ways to modify the product price, maybe you know that you will use the Event - Observe or “Rewrite” if the “Event” is not supported at that time. However, the rewrite doesn’t accept the customization from two modules in the same file, that will make the conflict and you can’t change anything.

Coming with Magento 2 tutorial, I will teach you how to change the product price with plugin via the steps.

Overview of changing product price with plugin in Magento 2

Step 1: Add di.xml file

It is crucial to identify where the place you want to activate the plugin, and then add di.xml file. Here, the sample is the frontend area with the following content for the di.xml file.

<config>
  <type name="Magento\Catalog\Model\Product">
    <plugin name="change_product" type=" Mageplaza\HelloWorld\Plugin\Product " sortOrder="1" disabled="true"/>
  </type>
</config>

Step 2: Change the product price

Open folder “Mageplaza\HelloWorld\Plugin” to add new class Product.php. Please put the prefix “after” before one of two ways to change the product price:

  • Edit the values reported by an original method
  • Call some behaviors once an original method is called.

And the result when the original method getPrice() finishes is declared by the $result. For example, you will adjust the product price by multiply it with 2.

<?php
 
namespace Mageplaza\HelloWorld\Plugin;
 
class Product
{
    public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result)
    {
        return $result + 100;
    }
}

When step 2 has done, this means you can see the customization of the product price on the frontend. Hope you find it useful within running Magento 2 store.

Step 3: Flush Cache and Test

Flush cache and test the result

Related Topic





Enjoyed the tutorial? Spread it to your friends!

magento-2-tutorial
how-to
change
product-price
plugin

Brian Tran
Brian Tran
Senior Magento Developer who is passionate about development and love technology

Comments for How to change product price with Plugin in Magento 2

Please leave comments if you have any questions, feedbacks.

Module Development

We recommend:

You also may like these Magento 2 Extensions

One Step Checkout

$199
120 reviews

Layered Navigation

$99
61 reviews

Gift Card

$199
8 reviews

Reward Points

$99
8 reviews

Affiliate

$149
16 reviews

Shop By Brand

$99
19 reviews

People also searched for:

  • magento 2 how to change product price with plugin