Magento2 Category Name – How to Get Current Category Name by URL in Observer

magento2

I want to get category name by current url in the observer. I have tried most common code but not working, so I am trying to get category name or id by current url.
For example, current url is : http://example.php/food.html.
Here I want category id by this url.

I have tried this in my observer :

namespace Mymodule\Event\Observer\Logger;
use Magento\Framework\Registry;

class GlobalLogger implements ObserverInterface
{
    protected $registry;

    public function __construct(
        \Magento\Framework\Registry $registry
) {
        $this->registry = $registry;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    { 
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
        echo $category->getId();
        echo $category->getName();
    }
}

Anyone have an idea for that, please?

Best Answer

You just need to check first whether current request is from category page and if from category then you need to call below code,

namespace Mymodule\Event\Observer\Logger;
use Magento\Framework\Registry;
class GlobalLogger implements ObserverInterface
{
    protected $registry;
    protected $request;

    public function __construct(
        \Magento\Framework\Registry $registry,
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->registry = $registry;
        $this->request = $request;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    { 
        if($this->getRequest()->getActionName() == 'category'){ 
            $category = $this->registry->registry('current_category');//get current category
            echo $category->getId();
            echo $category->getName();
        }
     }
 }

Remove var and generated folder from root and check again.