In Magento 2, blocks are PHP classes used to connect or create a link between layout and templates.
We, developers, sometimes require to place the related template file into the override block with the same directory path as the original when we override the widget block class.
Hence, to override catalog widget block in Magento 2, you need to follow the below steps:
Method To Override Catalog Widget Block in Magento 2:
1. Create di.xml file at app/code/Vendor/Module/etc into your custom module
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\CatalogWidget\Block\Product\ProductsList" type="Vendor\Module\Block\Product\ProductsList" /> </config>
2. Create a block file ProductsList.php at app/code/Vendor/Module/Block/Product to extend the widget class
<?php namespace Vendor\Module\Block\Product; class ProductsList extends \Magento\CatalogWidget\Block\Product\ProductsList { }
3. Copy the related template file and put into your custom module with related Path
vendor/magento/module-catalog-widget/view/frontend/templates/product/widget/content/grid.phtml
to
app/code/Vendor/Module/view/frontend/templates/product/widget/content/grid.phtml
Make sure another module has not used the same preference in di.xml
That’s it.
As a store owner Magento 2 override product view page social meta tags,it will help you to hide social meta tag or dynamically change content of social meta tags.
Feel free to share the post with fellow developers via social media.
You can also refer to the relevant solution to override block, model, and controller in Magento 2 that I posted earlier.
Thanks.