Magento 2 Get Category URL

Today’s discussion is about how to get a category URL in Magento 2. This is a program based tutorial to guide on how to get a category URL from category objects. Following this example can benefit you to obtain the category URL and other data like name etc. Let’s start with our example now.

Below is an example:

namespace QaisarSatti\Module\Block;

class Category extends \Magento\Framework\View\Element\Template
{

  protected $_categoryRepository;
  protected $_storeManager;  


  public function __construct(
\Magento\Store\Model\StoreManagerInterface $_storeManager,        
\Magento\Catalog\Model\CategoryRepository $_categoryRepository,
    ) {


        $this->_categoryRepository = $_categoryRepository;
   $this->_storeManager = $_storeManager;
     
    }
    public function getLoadCategory()
    {
$category_id=7; $_category=$this->categoryRepository->get($category_id,$this->_storeManager->getStore()->getId());
return $_category->getUrl();
 
    }

}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!