0

How to add custom text attribute on the product page after price Only if special price. If special price custom text is visible if normal price custom text is not visible. Magento 2.3.6

For example: Product 1 with special price, text "custom text aaa" visible. If product with regular price only, the text not visible.

Product 2 with special price, text "custom text bbb" visible. If product with regular price only, the text not visible.

1 Answer 1

0

app/code/YourVendor/YourModule/etc/di.xml

<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\View\Details">
       <plugin name="YourVendor_YourModule::add_custom_text" type="YourVendor\YourModule\Plugin\ProductViewDetailsPlugin" />
   </type>
</config>

app/code/YourVendor/YourModule/Plugin/ProductViewDetailsPlugin.php

<?php
namespace YourVendor\YourModule\Plugin;

use Magento\Catalog\Block\Product\View\Details as ProductViewDetails;
use Magento\Framework\Pricing\Render as PricingRender;

class ProductViewDetailsPlugin
{
    public function afterToHtml(ProductViewDetails $subject, $result)
    {
        $specialPrice = $subject->getProduct()->getSpecialPrice();
        if ($specialPrice !== null) {
            $customText = 'Your custom text goes here.';
            $priceRender = $subject->getLayout()->getBlock('product.price.render.default');
            if ($priceRender instanceof PricingRender) {
                $result .= '<div class="custom-text">' . $customText . '</div>';
            }
        }
        return $result;
    }
}
2
  • You answer is correct, but I am looking for another solution and my question was not very specific. In backend, product setting I want add text and I would like the text to be visible only if special price. Different text for different products.
    – Tom
    Feb 19 at 18:40
  • you need to create a custom product text type attribute and get its value by product id Feb 19 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.