There are 5 steps to create a new widget in Magento 2 (Magento 2.3)
- Step 1: Initialize widget
- Step 2: Create a widget template
- Step 3: Create a widget block
- Step 4: Flush Cache
- Step 5: Post Widget
Contents
Step 1: Initialize widget
File directory: app/code/Magestore/HelloMagento/etc/widget.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" ?> <widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:hellomagento:Magento_Widget:etc/widget.xsd"> <widget class="Magestore\HelloMagento\Block\Widget\Posts" id="magestore_hellomagento_posts"> <label>New Widget</label> <description>Posts</description> <parameters> <parameter name="posts" sort_order="0" visible="true" xsi:type="text"> <label>New Widget</label> </parameter> </parameters> </widget> </widgets> |
Step 2: Create a widget template
File directory: app/code/Magestore/HelloMagento/view/frontend/templates/widget/posts.phtml
1 2 3 4 |
<?php if($block->getData('posts')): ?> <h2 class='posts'><?php echo $block->getData('posts'); ?></h2> <p>Widget Sample</p> <?php endif; ?> |
Step 3: Create a widget block
File directory: app/code/Magestore/HelloMagento/Block/Widget/Posts.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace Magestore\HelloMagento\Block\Widget; use Magento\Framework\View\Element\Template; use Magento\Widget\Block\BlockInterface; class Posts extends Template implements BlockInterface { protected $_template = "widget/posts.phtml"; } |
Step 4: Flush Cache
Open terminal and use this command:
Php bin/magento cache:flush
Step 5: Post widget
Go to admin panel > Content > Pages > Home page > Edit
In Content tab, click on Insert Widget icon. You will see the New Widget in widget list
