Magento 2: force 404 based on category attribute
-
24-03-2021 - |
Question
I have created a custom eav attribute for categeories (bool). If set to "no" a category page should present a 404 page.
I have created an observer for the event layout_load_before
in which I would like to check the category and redirect to a 404 page if the conditions are met.
While "redirect" (as in a http 301 redirect) is not the proper term as I would like a direct 404 response instead.
I have tried throw new NotFoundException(__('Not found'));
. It actually sends a 404 response header but the underlying category page gets rendered nonetheless.
This is my observer's execute function:
public function execute(\Magento\Framework\Event\Observer $observer)
{
if ($observer->getFullActionName() == 'catalog_category_view'){
$cat = $this->_registry->registry('current_category');
if (!$cat->getData('cat404')) {
throw new NotFoundException(__('Not found'));
}
}
}
Any idea?
Thank you
Solution
I figured best way to do it is to use a plugin on the category model method getIsActive:
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Model\Category">
<plugin name="vendor_module_plugin_category" type="Vendor\Module\Plugin\Category" sortOrder="1"/>
</type>
</config>
Plugin:
namespace Vendor\Module\Plugin;
class Category
{
/**
* @param \Magento\Catalog\Model\Category $category
* @return bool
*/
public function afterGetIsActive(\Magento\Catalog\Model\Category $category)
{
return ($category->getData('cat404') ? true : false);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange