How to Add a Custom Widget to a Magento 2 Theme?

A widget is just a tool used to insert or edit content into a CMS Page Block or Page itself. In Magento 2, widgets are a powerful functionality in the configuration. For the store owners, widgets can be used to improvise the storefront with a lively interface. The widgets allow showing static information or dynamic content to the CMS pages or blocks. In Magento 2, widgets can be added to any CMS block in order to display any specific content or elements. Any customization of the widgets in Magento 2 is equal to the optimized front-end extension with a simple module. There are a few default widgets that come along with Magento 2, but to add any custom widget is a task that requires special attention.

How to Add a Custom Widget to a Magento 2 Theme

Hence, here is a step-by-step guide to creating a custom widget in Magento 2 theme.

Step 1. Declare Widget

Create a file etc/widget.xml with the help of the following content

<?xml version="1.0" ?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:helloworld:Magento_Widget:etc/widget.xsd">
<widget class="MageDelight\HelloWorld\Block\Widget\Posts" id="MageDelight_helloworld_posts">
<label>Blog Posts</label>
<description>Posts</description>
<parameters>
<parameter name="posts" sort_order="10" visible="true" xsi:type="text">
<label>Custom Posts Label</label>
</parameter>
</parameters>
</widget>
</widgets>

Step 2. Create a Widget Template File in Magento 2

File: view/frontend/templates/widget/posts.phtml

<?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; ?>

Step 3. Create Widget Block Class

Create block file: Block/Widget/Posts.php

<?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; ?>

And there you go. Make sure you flush the cache before you go ahead.

It is easy to go process for store owners to add widgets to a Magento 2 store theme. We hope that this turns out to be a helpful process for you, still, if you face any issues, feel free to reach us out.

Also read: How to Add New Products List in Widget in Magento 2?