How To Create A Custom Widget In Magento 2

Steps to create a custom widget in Magento 2

Create widget.xml

Directory

VendorName/ModuleName/etc/widget.xml

Content For widget.xml

<?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="VendorName\ModuleName\Block\Widget\Posts" id="vendorname_modulename_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>

Create a widget template file

Directory

VendorName/ModuleName/view/frontend/templates/widget/posts.phtml

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

Create Widget Block

Directory

VendorName/ModuleName/Block/Widget/Posts.php

Content for Posts.php

<?php 
namespace VendorName\ModuleName\Block\Widget;

use Magento\Framework\View\Element\Template;
use Magento\Widget\Block\BlockInterface; 
 
class Posts extends Template implements BlockInterface {

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

}

Flush or Clean Cache

To clean cache, run the following command.

php bin/magento cache:clean

If you are looking for Magento Developer, Visit Magento Web Agency.

Related Posts
  1. How To Add Configurable Product In Magento 2
  2. Setup Multiple Stores in Magento 2
  3. BENEFITS OF HAVING MAGENTO 2 UX
  4. Benefits of Magento 2 Improved Layered Navigation