To change the product price with a plugin in Magento 2, you'll need to create a custom module and implement an "after" plugin for the appropriate Magento 2 product price-related method. The "after" plugin allows you to modify the output or return value of a method without directly modifying the original method.
Here's a step-by-step example of how to change the product price using a plugin in Magento 2:
Step 1: Create a custom module Create a new module in the app/code directory of your Magento 2 installation. Let's name the vendor module "Simple/IncreasePrice".
Step 2: Define module files In the module's folder, create the necessary files:
- 1. Create the registration.php file:
File path: app/code/Simple/IncreasePrice/registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Simple_IncreasePrice', __DIR__ );
- 1. Create the module.xml file:
File path: app/code/Simple/IncreasePrice/etc/module.xml
<?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="Simple_IncreasePrice" setup_version="1.0.0"> </module> </config>
Step 3: Create the plugin class Next, create the plugin class that will modify the product price:
File path: app/code/Simple/IncreasePrice/Plugin/Price.php
<?php declare(strict_types=1); namespace Simple\IncreasePrice\Plugin; use Magento\Catalog\Model\Product; /** * package Price */ class Price { /** * @param Product $product * @param $price * @return float */ public function aftergetPrice(Product $subject, $price): float { $price = $subject->getData('price'); return $price + $price * 0.25; } }
Step 4: Declare the plugin in di.xml Now, declare the plugin in the di.xml file to make it active:
File path: app/code/Simple/IncreasePrice/etc/di.xml
<?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" type="Simple\IncreasePrice\Plugin\Price" sortOrder="1" disabled="false"/> </type> </config>
After completing these steps, your plugin will be active, and whenever the getPrice
method of the Magento\Catalog\Model\Product
class is called, it will modify the product price according to your custom logic.
Keep in mind that this example demonstrates how to modify the product price globally. Depending on your requirements, you may want to add additional conditions or logic to modify prices selectively based on various factors such as customer groups, product types, or other attributes.

No comments: