How to Create a Widget in Magento 2 Store

It only takes four easy steps to complete the task so we hope you will succeed on this thing. For more assistance, contact us as we are all set to assist you anytime.

For your website, creating such Widget will lead to numerous advantages such as a dynamic product data, enhanced promotional images on front locations and a lot more. Knowing the fact that widgets exist to add ease in the viewing and surfing on your website, it would be best to know how to make use of this Widget in your Magento 2.

To get started, you need to first initialize the Widget by creating a file etc/widget.xml with the following code content:

<?xml version=”1.0″ ?>

<widgets xmlns:xsi=”” xsi:noNamespaceSchemaLocation=”urn:magento:helloworld:Magento_Widget:etc/widget.xsd”>

<widget class=”sparxbpo\HelloWorld\Block\Widget\Posts” id=”sparxbpo_helloworld_posts”>

<label>Blog Posts</label>



<parameter name=”posts” sort_order=”10″ visible=”true” xsi:type=”text”>

<label>Custom Posts Label</label>





Next thing to do is to create a Widget Template File. Do this by creating a file with the path view/frontend/templates/widget/posts.phtml where this code will be added:

<?php if($block->getData(‘posts’)): ?>

<h2 class=’posts’><?php echo $block->getData(‘posts’); ?></h2>

<p>This is sample widget. Perform your code here.</p>

<?php endif; ?>

Create then a Widget Block Class through the Block/Widget/Posts.php with the code below:


namespace sparxbpo\HelloWorld\Block\Widget;

use Magento\Framework\View\Element\Template;

use Magento\Widget\Block\BlockInterface;

class Posts extends Template implements BlockInterface


protected $_template = “widget/posts.phtml”;


And lastly, post the widget. First, flush cache by opening SSH terminal and run this command in the root directory of Magento 2: php bin/magento cache:flush. From here, go to the Admin panel > Content > Pages > Homepage > Edit

In the Content tab and click on Insert Widget icon. As a result, you will expect the Blog posts in the widget list.


About us:

Total Magento 2 development services  including Magento 2 theme development, Magento 2 upgrade services, Magento 2 B2B eCommerce Solutions, Magento 2 Marketplace Development.

Don’t Miss:

A full services magento 2 development company for your end-to-end magento 2 solutions.

Similar eCommerce solutions:


Posted on:
Post author

Leave a comment

Your email address will not be published. Required fields are marked *