Magento2 Plugin – How to Overwrite Function Using Plugin Method

magento2plugin

I want to customize return value of $block->getProductDetailsHtml($_product) (in list.phtml) using plugin method, not overrite list.phtml

Best Answer

Block Magento\Catalog\Block\Product\ListProduct extends Magento\Catalog\Block\Product\AbstractProduct. AbstractProduct have getProductDetailsHtml($_product) so you need to add plugin for AbstractProduct

Vendor/Module/etc/frontend/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\Block\Product\AbstractProduct">
            <plugin name="vendor.module.category.products.list" type="Vendor\Module\Plugin\Block\Product\AbstractProduct" />
        </type>

    </config>

Vendor/Module/Plugin/Block/Product/AbstractProduct.php

    <?php

    namespace Vendor\Module\Plugin\Block\Product;

    class AbstractProduct
    {
        public function afterGetProductDetailsHtml(
            \Magento\Catalog\Block\Product\AbstractProduct $subject,
            $result
        ) {
             // $result contains the original values
             // do the stuff to change $results 
             // easy for your reference I just pass below string
             return '<b>test</b>';
        }
    }       

Note: We can use after, before, around so you need to decide which is the best suite for you. Refer this link for how to use.

I have checked, it works

easy for your reference

Related Topic