With the observer class below, I'm trying to set noindex and nofollow on a category page. I'm unable to get the code to first check if it is a category page and then set noindex if the title of the category page has "parts" in the category name. Can you please help find this out.
<?php
namespace Perfectmakeupmirrors\PmmHead\Observer;
use Magento\Framework\Event\ObserverInterface;
use \Magento\Framework\Event\Observer;
use Magento\Framework\Registry;
use \Psr\Log\LoggerInterface;
class SetRobotsMetaTag implements ObserverInterface
{
protected $request;
protected $registry;
protected $layoutFactory;
protected $logger;
public function __construct(
\Magento\Framework\App\Request\Http $request,
\Magento\Framework\Registry $registry,
\Magento\Framework\View\Page\Config $layoutFactory,
LoggerInterface $logger)
{
$this->registry = $registry;
$this->request = $request;
$this->layoutFactory = $layoutFactory;
$this->logger = $logger;
}
public function execute(Observer $observer) {
$this->logger->debug("Observer is watching");
$this->logger->debug("Action Name = " . $this->request->getActionName());
$this->layoutFactory->setRobots('NOINDEX,NOFOLLOW');
if ($this->request->getActionName() == 'category') {
$category = $this->registry->registry('current_category');
$categoryName = $category->getName();
$this->logger->debug("Category Name = $categoryName");
if (stripos($categoryName, 'part') !== false) {
$this->logger->debug("Robots Set");
$this->layoutFactory->setRobots('NOINDEX,NOFOLLOW');
}
}
}
}
CodePudding user response:
Update your function condition.
public function execute(Observer $observer) {
$category = $this->registry->registry('current_category');
$categoryName = $category->getName();
$categoryName = trim($categoryName);
$this->layoutFactory->setRobots('INDEX,FOLLOW');
if (stripos($categoryName, 'Parts') !== false) {
$this->layoutFactory->setRobots('NOINDEX,NOFOLLOW');
}
}