Magento 2 – How to Get Category URL by ID

category-attributemagento-2.1magento2urlurl-key

I'm trying to get the URL key of any given category with the ID. I have this;

$categoryId = 3;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$object_manager = $_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
print_r($object_manager->getData());

And this works (in the print_r there is the URL key I need), but category #3 is the top-level category. Whenever I try any subcategory (say ID 5) I get a blank array.
I'm just lost for words, can't figure it out.

In Magento 1.x I used to do this: Mage::getModel('catalog/category')->load($catID)->getUrl() and that worked.

TL;DR: This code works, change the ID to a (correct) category ID and change getData() to getUrl() for the complete category url, or getName() for the category name.

Best Answer

In order to get the category url you need to use the \Magento\Catalog\Model\Category function getUrl() like so:

$category->getUrl()

Also, you can get url by CategoryRepositoryInterface

nameSpace ['Your_nameSpace'] 
use Magento\Catalog\Api\CategoryRepositoryInterface;
class ['Your_Class_name']
    protected $_storeManager;
    protected $categoryRepository;
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,
    ) {
        .........
        $this->_storeManager = $storeManager;
        $this->categoryRepository = $categoryRepository;
    }

     public  function getCategory()
    {
            $category = $this->categoryRepository->get($categoryId, $this->_storeManager->getStore()->getId());

        return $category->getUrl();
    }
} 
Related Topic