This blog was updated on Aug 8th, 2017 based on readers’ feedback.
Magento 2 developers have a need to create category widgets that can be positioned in any page of the store. This blog provides the complete code to create such a widget that will display the categories along with their respective sub-categories.
Create a module. Refer the blog How to create a module in Magento 2?
To begin with, we need to create an XML that should render and indicate the widget.
Create widget.xml in app/code/Companyname/Modulename/etc/. Here, for instance, Company name will be Dckap and module name will be Showcategories.
In the above code, we get category-id as parameters to get displayed wherever the widget is called.
When you navigate to the admin -> content -> widgets -> Add New, you will see the page as seen below
Now we need to create a Block file in the path app/code/Dckap/Showcategories/Block/Showcategories.php as specified in the widget.xml class=”Dckap\Showcategories\Block\Widget\Showcategories”.
In this block, we are going to collect all the data to show the categories and their subcategories along with the image.
In this step, we are going to create a phtml in the path app/code/Dckap/Showcategories/view/frontend/templates/widget/showcategories.phtml
Once finished, follow usual Magento procedures like setup:upgrade, cache flush etc
Now the widget is ready to show specific categories in the pages you want. The pages can be selected in the page layouts.
Please refer the screenshot below.
Was this helpful? Please let us know your feedback.