Magento – Magento 2 How To Add Custom Text After All Prices

event-observerformatmagento2price

I tried to add custom text after all prices that appears in magento 2.

For this I tried to do in 2 ways:

1) I tried to modify function getPrice from module-catalog\Model\Product.php like this:

public function getPrice()
    {
        if ($this->_calculatePrice || !$this->getData(self::PRICE)) {
           return $this->getPriceModel()->getPrice($this)."some text";
        } else {
            return $this->getData(self::PRICE);
        }
    }

but this is not working. If I add some int value this will work on every page, othewise is show 0.

if I will do this: return $this->getPriceModel()->getPrice($this)* 100; this will work.

I tried to add this custom text on "currency_display_options_forming" event like this:

   public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $baseCode = $observer->getEvent()->getBaseCode();
        $currencyOptions = $observer->getEvent()->getCurrencyOptions();


        if ($baseCode === 'EUR') { // change currency symbol position to Right with EUR
            $currencyOptions->setData('position', \Magento\Framework\Currency::RIGHT)."some text";

        }

        return $this;
    }
}

This is also not working.

Does anyone have a good idea how to do that?

Maybe I should find function that format this value from getPrice function? if yes, is somebody that know where I can find this function?

Best Answer

You can use magento's plugin functionality Create di.xml file in etc > frontend > di.xml

Put below code

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Block\Product\ListProduct" shared="false">
        <plugin name="vendor_module_product_list_text" type="Vendor\Module\Plugin\ProductListPlugin" disabled="false" sortOrder="999" />
    </type>
</config>  

Create plugin file

namespace Vendor\Module\Plugin;

class ProductListPlugin {

    /**
     * @param Product $product
     * @return string
     */
    public function afterGetProductPrice($subject, $result, $product)
    {
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get(\Psr\Log\LoggerInterface::class);
        $logger->info($result);

        $subscriptionTextHTML = '<div class="custom_text"><span>It will display</span></div>';

        return $result.$subscriptionTextHTML;
    }

}

That's all.

Related Topic