Remove a layout block on condition

Do you want to remove a block from the layout on a specific condition? You just need to use a Magento event to do that. Let's check it together.

To remove a block from the layout on a specific condition we will need the Magento event "layout_generate_blocks_after" which is called after the page layout blocks are generated. So lets define our event.

As you can see the class instance that is defined to be used is the RemoveBlockOnConditionObserver. So on the observer class below where the execute function is the one that will be called we add our condition to remove the block that we want.

First we get the block by name from the layout. If the block exists then we can add our condition and if it's true, then we remove the block from the layout using the unsetElement function.

Please notice that the example above is not gonna work on the pages that the full page cache is enabled.

Feel free to share this post and ask your questions in the comments below.

Till next time!