Question

I want to change the product price on frontend programmatically with plugin in Magento 2. Here is what I have done so far.

app/code/Vendor/ModuleName/etc/frontend/di.xml

<config>
   <type name="Magento\Catalog\Model\Product">
       <plugin name="cache_price" type="Vendor\ModuleName\Plugin\Product" sortOrder="1" disabled="true"/>
   </type>
</config>

app/code/Vendor/ModuleName/Plugin/Product.php

<?php
namespace Vendor\ModuleName\Plugin;

class Product
{
   public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result)
   {
    return $result + 100;
   }
}

app/code/Vendor/ModuleName/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="Vendor_ModuleName" setup_version="2.0.1">
    <sequence>
        <module name="Magento_Checkout" setup_version="100.0.6"/>
    </sequence>
</module>
</config>

But when I see the product page on frontend, nothing is changed in product price. What I am doing wrong?

Was it helpful?

Solution

Just replace this code

<plugin name="cache_price" type="Vendor\ModuleName\Plugin\Product" sortOrder="1" disabled="true"/>

with

<plugin name="cache_price" type="Vendor\ModuleName\Plugin\Product" sortOrder="1" />

You have apply disabled="true" code in di.xml

OTHER TIPS

Check following class

# Magento/Catalog/Pricing/Price/FinalPrice.php

/**
 * Retrieve base price instance lazily
 *
 * @return BasePrice|\Magento\Framework\Pricing\Price\PriceInterface
 */
protected function getBasePrice()
{
    if (!$this->basePrice) {
        $this->basePrice = $this->priceInfo->getPrice(BasePrice::PRICE_CODE);
    }
    return $this->basePrice;
}

So you need to pluginize following class Magento/Catalog/Pricing/Price/BasePrice.php

/**
 * Get Base Price Value
 *
 * @return float|bool
 */
public function getValue()
{
    if ($this->value === null) {
        $this->value = false;
        foreach ($this->priceInfo->getPrices() as $price) {
            if ($price instanceof BasePriceProviderInterface && $price->getValue() !== false) {
                $this->value = min($price->getValue(), $this->value ?: $price->getValue());
            }
        }
    }
    return $this->value;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top