Magento 2 How To Create Custom Widget.

Hello Guys! 👋

The widget is a powerful feature provided by Magento 2 to add static or dynamic content to store pages.

Some of the widgets provided by Magento are default in the system following list is a default inbuilt widget provided by Magento.

  • CMS Page Link
  • CMS Static Block
  • Catalog Category Link
  • Catalog New Products List
  • Catalog Product Link
  • Catalog Products List
  • Orders and Returns
  • Recently compared Products
  • Recently Viewed Products

In this blog, we create a custom widget. Follow following step to create custom widget.

Step 1: Add widget.xml in following path:
app\code\Vendor\Extension\etc
<?xml version="1.0" ?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
    <widget class="Vendor\Extension\Block\Widget\Customwidget" id="customwidget">
        <label>Custom Widget</label>
        <description></description>
        <parameters>
            <parameter name="favourite_fruit" xsi:type="select" visible="true" required="true" sort_order="20">
                <label translate="true">Favourite Fruit</label>
                <options>
                    <option name="apple" value="Apple">
                        <label>Apple</label>
                    </option>
                    <option name="pear" value="Pear" selected="true">
                        <label>Pear</label>
                    </option>
                    <option name="orange" value="Orange">
                        <label>Orange</label>
                    </option>
                </options>
            </parameter>
        </parameters>

    </widget>
</widgets>

Step 2: Add Customwidget.php in following path
app\code\Vendor\Extension\Block\Widget
<?php

namespace Vendor\Extension\Block\Widget;

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

class Customwidget extends Template implements BlockInterface
{

    protected $_template = "widget/customwidget.phtml";

}

Step 3: Now add customwidget.phtml in following path
app\code\Vendor\Extension\view\frontend\templates\widget
<?php if($block->getData('favourite_fruit')): ?>
    <h2 class='title'> <?= __("Favourite Fruit") ?> <?php echo $block->getData('favourite_fruit'); ?></h2>
<?php endif; ?>

Now insert widget to cms pages from admin panel.

Hope! It will help you

Thank you 😊

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 14

No votes so far! Be the first to rate this post.

Leave a Reply

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