Magento2 - Get category URL by ID
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();
}
}
Always try to use repository. You need to inject following way:
/** * @var \Magento\Catalog\Helper\Category */ protected $categoryHelper; /** * @var \Magento\Catalog\Model\CategoryRepository */ protected $categoryRepository; public function __construct( \Magento\Catalog\Helper\Category $categoryHelper, \Magento\Catalog\Model\CategoryRepository $categoryRepository, ) { $this->categoryHelper = $categoryHelper; $this->categoryRepository = $categoryRepository; }
For category url
$categoryId = 3; $categoryObj = $this->categoryRepository->get($categoryId); echo $this->categoryHelper->getCategoryUrl($categoryObj);
You can try below code.
$categoryId = 5;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$object_manager = $_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
echo "<pre>";
print_r($object_manager->getData());
Before you use a category id you have confirm category id exists in admin or it will return an empty array.
Let me know if you have any questions.