How To Override Catalog Widget Block in Magento 2
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:
- Create di.xml file at app/code/Vendor/Module/etc into your custom module
1234<?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> - Create a block file ProductsList.php at app/code/Vendor/Module/Block/Product to extend the widget class
12345<?phpnamespace Vendor\Module\Block\Product;class ProductsList extends \Magento\CatalogWidget\Block\Product\ProductsList{} - 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.
I’ve tried to keep it simple. However, if you find any doubts about the implementation of the above solution, do mention them in the Comments section below.
I’d be glad to help you out.
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.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How To Load Products by SKU in Magento 2
How To Check If Product With SKU Exists in Magento 2
Next