Programmatically: How to create a custom widget in Magento 2
Step 1: Create a new module
Create a new directory for your module in the app/code directory, e.g., MyCompany/MyModule.
Inside the MyModule directory, create the following files:
// mymodule.xml
// composer.json
{
"name": "mycompany/mymodule",
"description": "My Custom Module",
"version": "1.0.0",
"require": {
"magento/framework": "~101.0"
},
"autoload": {
"psr-4": {
"MyCompany\\MyModule\\": ""
}
}
}
Step 2: Create the widget class
In the src directory of your module, create a new file called Widget.php:
// src/Widget.php
namespace MyCompany\MyModule\Block Widget;
use Magento\Framework\View\Element\Html\Widget\AbstractWidget;
class MyCustomWidget extends AbstractWidget
{
protected $template = 'MyCompany_MyModule::widget/mywidget.phtml';
public function getHtml()
{
return 'Hello, World!
';
}
}
In this example, we're creating a simple widget that returns a hardcoded HTML string.
Step 3: Define the widget in the configuration
In the etc/di.xml file of your module, add the following code:
This defines a preference for the Magento\Framework\View\Element\Html\WidgetFactory class, which will be used to create instances of our custom widget.
Step 4: Register the widget
In the etc/widget.xml file of your module, add the following code:
This registers our custom widget with the Magento system.
Step 5: Use the widget in your theme
To use your custom widget in your theme, you'll need to create a new layout file (e.g., local.xml) in the view/frontend/base/default directory of your theme.
In this file, add the following code:
This adds an instance of our custom widget to the content block in our theme.