Select Page

How to set NOINDEX, NOFOLLOW on specific page programmatically Magento2

Radhika Garg
Published: May 20, 2022

In this guide, we will learn how can we change the robots of a particular page.

There are several options for robots available that you can choose from:

  • INDEX, FOLLOW – If you want web crawlers to index a page and follow the links on that page.
  • NOINDEX, FOLLOW – If you don’t want web crawlers to index a page but want them to follow the links on that page.
  • INDEX, NOFOLLOW – If you want web crawlers to index a page and don’t want them to follow the links on that page.
  • NOINDEX, NOFOLLOW – If you want web crawlers neither to index a page nor to follow the links on that page.

Now let’s see how we can set NOINDEX, NOFOLLOW on a particular page programmatically.

Step 1 – You need to create di.xml in the below path:
app/code/Vendor/ModuleName/etc/frontend/di.xml

<?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\Framework\View\Page\Config\Renderer">
        <plugin name="seoRender" type="Webkul\Demo\Plugin\Robots"/>
    </type>
</config>

Step 2 – Now you need to create Robots.php in the below path:
app/code/Vendor/ModuleName/Plugin/Robots.php
And, add the below code

<?php
namespace Webkul\Demo\Plugin;
use Magento\Framework\App\Request\Http;
use Magento\Framework\View\Page\Config as PageConfig;
use Magento\Framework\View\Page\Config\Renderer;
class Robots
{
    protected $pageConfig;
    protected $request;
    /**
     *
     * @param PageConfig $pageConfig
     * @param Http $request
     */
    public function __construct(
        PageConfig $pageConfig,
        Http $request
    ) {
        $this->pageConfig = $pageConfig;
        $this->request = $request;
    }
    /**
     * Before Render function
     *
     * @param Renderer $subject
     */
    public function beforeRenderMetadata(Renderer $subject)
    {
        $fullActionName = $this->request->getFullActionName();
        if ($fullActionName == 'catalog_product_view') {
            $this->pageConfig->setMetadata('robots', 'NOINDEX,NOFOLLOW');
        }
    }
}

That’s all about the setting NOINDEX, NOFOLLOW on specific page . If you have any questions please comment below, and we will try to respond to you.
Happy Coding!!

Source: webkul.com