Update Layout on Attribute set

Would you like to have a custom layout for products that belong to a specific attribute set. Let's see together how you can add a layout handler for that.

As might you have noticed in Magento 2, there are some layout handlers by default that you can use, depending on product Id, product SKU and product type. The update of the layout with these handlers is happening on the Magento\Catalog\Helper\Product\View class and more specific on the initProductLayout function which initialises the layout for viewing product page.

Now to add a new one depending on the product attribute set, you will need to create a plugin for this function before is called and add our custom handler by calling the function addPageLayoutHandles as below.

So now you can use our new layout handler depend on the product attribute set like:


The full example as extension can be found here. To make it work for your attribute set, do not forget to rename the file catalog_product_view_attribute_set_id_17.xml using your attribute set id and add your code.

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

Till next time!

DigitalOcean Referral Badge