This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Here’s How You Can Create a Custom Widget in Magento 2

May 31, 2021

4 Min Read

Widgets are used to add static or dynamic content to the CMS pages and blocks in Magento 2. They are reusable elements providing different functionalities that can be added in any CMS block of Magento 2 store. Widgets are essential because they help visitors to view and surf your Magento 2 store with ease. It plays an important part in creating beautiful designs and templates in Magento 2, providing better user experience.

From the technical side, a widget is a Magento 2 module, which is designed with a set of advanced configuration options. Thanks to the great flexibility and control, widgets provide information and content directly using the Magento admin panel. The best part is that you can call a widget from anywhere on the Magento 2 store.

In this article, I will demonstrate how to create a custom widget in Magento 2 and use it on the homepage of the store. You can also create widget templates as per your desire.

Scale Your Magento 2 Store With Ease

One-Click Magento installation with your own managed hosting solution.

So, let’s start with the basics. I think we all know how to create a module in Magento 2, right? In case you’re not familiar with it, here’s the link to an excellent tutorial that covers the simple process of creating a module in Magento 2 in-depth.

Now, let’s move on to the step-by-step process of creating a custom widget in Magento 2. First, create a new module using Cloudways as namespace and CustomWidget as the module name and create registration.php at Magento2_Root/app/code/Cloudways/CustomWidget/ directory.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Cloudways_CustomWidget',
    __DIR__
);

Cloudways Magento Hosting For Developers

Now, create a module.xml at Cloudways/CustomWidget/etc/ and add the following code.

<?xml version="1.0" ?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
            <module name="Cloudways_CustomWidget" setup_version="1.0.0"/>
</config>

Next, you’ll need to create a widget.xml configuration file at Cloudways/CustomWidget/etc/ with the following code.

<?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="Cloudways\CustomWidget\Block\Widget\Samplewidget" id="cloudways_customwidget_samplewidget">
                        <label>Cloudways Sample Widget</label>
                        <description></description>
                        <parameters>
                                    <parameter name="widgettitle" sort_order="10" visible="true" xsi:type="text">
                                                <label>Title</label>
                                    </parameter>
                                    <parameter name="widgetcontent" sort_order="20" visible="true" xsi:type="textarea">
                                                <label>Content</label>
                                    </parameter>
                        </parameters>
            </widget>
</widgets>

In the abovementioned code, I have declared two input fields with labels Title and Content. Whatever the widget is called, it will display the value of both the fields. In the <widget> tag, I have declared a block class, Cloudways\CustomWidget\Block\Widget\Samplewidget that instructs our widget to use the particular template.

Now, I am going to create a block file named Samplewidget.php in Cloudways/CustomWidget/Block/Widget/ directory with the following code.

<?php
namespace Cloudways\CustomWidget\Block\Widget;

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

class Samplewidget extends Template implements BlockInterface
{
    protected $_template = "widget/samplewidget.phtml";
}

In the above code, I have assigned a template file inside the $_template variable. Now, create a widget template file samplewidget.phtml in Cloudways/CustomWidget/view/frontend/templates/widget with the following code.

<?php if($block->getData('widgettitle')): ?>
            <h2 class='cloudways-title'><?php echo $block->getData('widgettitle'); ?></h2>
<?php endif; ?>
<?php if($block->getData('widgetcontent')): ?>
            <h2 class='cloudways-content'><?php echo $block->getData('widgetcontent'); ?></h2>
<?php endif; ?>

Here, as you can see that I have picked up the value from fields by calling $block->getData(‘parameter’); where the parameters are widgettitle and widgetcontent.

And that’s it! We have successfully created a custom widget in Magento 2. It’s time to check the end-result. Login to your Magento 2 Admin panel and navigate to Content > Pages.

Magento 2 Content Page

Click Edit in front of Homepage CMS page.

Magento 2 CMS Page

Expand the Content tab and tap Insert Widget icon.

Magento 2 Insert Widget Icon

Select Cloudways Sample Widget from the widget list.

Magento 2 Sample Widget

Enter the Title and Content to display on the homepage, hit Insert Widget button and save the page.

Magento 2 Insert Widget

Lastly, in order to make any changes, you will have to flush the Magento 2 cache. Launch CLI and run the following commands:

php bin/magento cache:clean
php bin/magento cache:flush

Load the front end of your store, and it will look like this.

Magento 2 Front Page

Conclusion

Well, this was all about creating a custom widget in Magento 2. The reason for writing this article is to provide you a precise tutorial starting from the basic steps, covering Magento 2 widget development, and calling it on the Magento 2 homepage.

If you have anything to add to this topic, feel free to share your thoughts in the comments section below.

Q: What is a Magento widget?

A: A Magento widget is a customizable block that is used to display static or dynamic content at specific locations on store pages. Some widgets are available by default and you can also develop custom widgets to extend the native functionalities.

Q: What Magento 2 blocks are available by default?

A: Magento 2 offers the following blocks by default: 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.

Q: How do I use Magento 2 widgets?

A:

Using Magento 2 widgets is a simple three-step process:

  1. Select the widget type in Content > Elements > Widgets
  2. Fill the fields in the Layout Updates section
  3. Place the Block

Remember to flush the cache so that the frontend loads the most recent display configurations.

Q: What is a block widget?

A: A block widget in Magento is essentially a non-editable block that is used as a placeholder for content on the pages. To use the block, you need the block ID.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Great speed, features, knowledgebase, dashboard, UX and fast, expert support. Very happy!”

Stefan [Management Consultant]

Fayyaz Khattak

Fayyaz, a passionate Motorbike tourist, works as a Team Lead — Magento Community at Cloudways - A Managed Magento Hosting Platform. His objective is to learn & share about PHP & Magento Development in Community. You can contact him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!