Once you know how to get URLs in Magento 2, you might also need to learn how to get the current category in Magento 2. Regardless if you want to provide discounts based on category or simply retrieve all category information, this guide will come in handy.
Get current category in Magento 2 in PHP class
<?php
namespace Vendor\Module\Folder;
class Example
{
private $registry;
public function __construct(Magento\Framework\Registry $registry)
{
$this->registry = $registry;
}
public function getCurrentCategory()
{
return $this->registry->registry('current_category');
}
}
Get current category in Magento 2 via Object Manager
<?php
$currentCategory = \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Framework\Registry::class)
->registry('current_category');
echo $currentCategory->getId();
echo $currentCategory->getName();
?>
Note: you should avoid direct use of the ObjectManager in your code since it hides real dependencies of the class.
So, as you can see, getting current category in Magento 2 is not that hard. Not harder than getting current store ID in Magento at least.