·

photo credit: bubble wrap : プチプチ via photopin (license)

Remove the wrapping paragraph around a widget in Magento 2

I already wrote a post about how to do this in Magento 1, but it seems that the ‘wrapping paragraphs around widgets‘-problem still exists in Magento 2. That’s why in this article I’ll show you how to fix this problem in Magento 2.

Create a module first

First things first, we need to create a new module in which we can manifest our awesome functionality. If you don’t know how to create a module in Magento 2, I’d suggest you read this article first.

Create a helper

The next thing we do, is create a helper class that has our method to remove the wrapping paragraphs. We call this file Data.php  and we place it in the Helper -folder of our module:

The removeWrappingParagraphs() -method is pretty straight forward: it uses some regular expressions to check if there are widgets that are wrapped in paragraphs or <div> -elements.

Register for the proper events

Now, there are 2 events that we want to listen for in our module:

  • cms_page_render , which is fired as soon as a CMS page is rendered.
  • cms_block_load_after , which is fired after a CMS block is loaded.

We only need to listen to these events on the frontend of our site, so create a file called events.xml  in etc/frontend  of your modules’ folder and add the following content:

Create the observers

In Magento 2, you need to create a separate observer file for each event that you register to. If you look at the XML above, you’ll note that we need to create 2 observers in Model/Observer/Cms :

PageRender.php

Note the execute() -method of this class, because that’s where the magic happens. It gets the page from our observer and manipulates it’s content by using the helper we created earlier.
At this point we’re already done for widgets in CMS pages. But as said, we want to remove them wrapping paragraphs in static blocks as well. That’s where the next file comes in:

BlockLoadAfter.php

The execute() -method of this class is more or less the same as that of PageRender , with the only difference that it manipulates the content of a block instead of a page.

That’s it!

That’s it! You’re done! You now have successfully created a module that removes wrapping paragraphs from widgets in CMS pages or static blocks in Magento 2! Want to know more about how events in Magento 2 work?

Visitors give this article an average rating of 4.8 out of 5.

How would you rate this article?

Leave a Reply