How to Override a phtml File Using a Custom Module in Magento 2

How to Override a phtml File Using a Custom Module in Magento 2

It is well known that customizing the core Magento 2 functionality is a bad coding practice. Once you upgrade the version, your efforts are in vain. Hence, it is advisable to override a function, class or file, as per the requirement.

Here, I’ll show you how to override a phtml file using a custom module in Magento 2.

There are two methods to do so as mentioned below:

Methods to Override a phtml file using a custom module in Magento 2:

  1. Create registration.php file in app\code\[Vendor]\[Namespace]\

  2. Create module.xml file in app\code\[Vendor]\[Namespace]\etc

Method 1: Override a phtml file using a custom module in Magento 2 with plugin

In this method, we use the method to create plugin in Magento 2

  1. Create di.xml file in app\code\[Vendor]\[Namespace]\etc

  2. Create Simple.php file in app\code\[Vendor]\[Namespace]\Plugin\Block\Product\View\Type

Method 2: Override a phtml file using a custom module in Magento 2 with xml

  1. Create catalog_product_view_type_simple.xml file in app\code\[Vendor]\[Namespace]\view\frontend\layout
     

That’s it.

The above example shows how to override a phtml file for product stock status. The default functionality to show out of stock is overridden to display an image.

Follow any of the above method suitable to you.

Please share your doubts on the topic in the Comments section below. I’d be happy to help.

Thank you.

 

5
(based on 5 Reviews)

Sanjay is a co-founder at Meetanshi. He is a certified Magento developer who loves creating Magento E-commerce solutions. When he is not engrossed with anything related to Magento, he loves to play cricket.

Leave a Reply