How to Create a Widget Programmatically in Magento 2

How to Create a Widget Programmatically in Magento 2

Hello Magento Friends,

In today’s blog, we will learn about How to Create a Widget Programmatically in Magento 2.

Widgets are components that can be added to any CMS block in Magento 2. Widgets are used to add static or dynamic content to CMS blocks or CMS pages. Widgets can improve the user interface on the storefront. Widgets can help to simplify the browsing of stores for the users.

So let’s look at How to Create Widget Programmatically in Magento 2.

Steps to Create a Widget Programmatically in Magento 2:

Step 1: To declare a custom widget create the widget.xml file at the below path

app\code\Vendor\Extention\etc\widget.xml

Now, add the below code

<?xml version="1.0" ?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:extention:Magento_Widget:etc/widget.xsd">
   <widget class="Vendor\Extention\Block\Customwidget" id="customwidget">
	<label>Custom Widget</label>
	<description>Creating Custom Widget</description>
	<parameters>
		<parameter name="customwidgettext" sort_order="10" visible="true" xsi:type="text">
			<label>Enter Custom text</label>
		</parameter>
	</parameters>
   </widget>
</widgets>

Parameters allow adding of different fields to the widget.

Step 2: Now, create a PHP file inside the Block. Go to below path

app\code\Vendor\Extention\Block\Customwidget.php

And add the code as follows

<?php
 
namespace Vendor\Extention\Block;

use Magento\Framework\View\Element\Template;
use Magento\Widget\Block\BlockInterface;

class Customwidget extends Template implements BlockInterface
{
	protected $template = "customwidget.phtml";
}

Step 3: Now create a phtml file, that will show the data of phtml to the frontend. Navigate to the following path

app\code\Vendor\Extention\view\frontend\templates\customwidget.phtml

Add the following code

<div>
   <p>This will show the custom text field data inside widget : </p>
   <span><?php echo $block->getData(‘customwidgettext’);?></span>
</div>

Conclusion:

This way you can create a widget programmatically in Magento 2. You can also Insert a Widget into Sidebar in Magento 2. If you have any doubts, let me know through the comment section.

Share the article and let your friends learn about creating a widget in Magento 2.

Keep connected with us for more!

Happy Coding!

Previous Article

How to Create Theme App Extension in Shopify-Laravel App

Next Article

Magento 2 Extensions Digest April 2022 (New Release & Updates)

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨