In Magento 2 I am looking to create a module that adds a custom 404 page specifically for not-found products in the catalog, however keep the default 404 page for all other pages.
My initial thoughts are to create a controller with di on \Magento\Catalog\Controller\Product\View
that checks if the product does not exist and changes the template to a custom 404 response if returned true.
Something like (not actual code)
public function execute()
{
if (!$this->productExists()) {
$this->setTemplate('custom-404');
}
}
Is there a better way to do this? Let me know if you need additional info.
Best Answer
Magento 2 provides some classes to handle no router:
vendor/magento/framework/App/Router/NoRouteHandler.php
vendor/magento/framework/App/Router/NoRouteHandlerInterface.php
vendor/magento/framework/App/Router/NoRouteHandlerList.php
Create an example module:
app/code/Boolfly/NotFoundPages/etc/module.xml
app/code/Boolfly/NotFoundPages/etc/frontend/routes.xml
app/code/Boolfly/NotFoundPages/etc/frontend/di.xml
app/code/Boolfly/NotFoundPages/Controller/NoRoute.php
app/code/Boolfly/NotFoundPages/Controller/NoRouteHandler.php
app/code/Boolfly/NotFoundPages/Controller/NoRoute/Product.php
app/code/Boolfly/NotFoundPages/Controller/NoRoute/Other.php
app/code/Boolfly/NotFoundPages/view/frontend/layout/notfoundpages_noroute_product.xml
app/code/Boolfly/NotFoundPages/view/frontend/layout/notfoundpages_noroute_other.xml
app/code/Boolfly/NotFoundPages/view/frontend/templates/product.phtml
app/code/Boolfly/NotFoundPages/view/frontend/templates/other.phtml
Now, we can try:
Other pages: url:
magen2.loc/dddddd
Product Page: url:
magen2.loc/catalog/view/45555
Note: we will catch the url of product with format:
{base url}/catalog/product/view/{....}