Magento – How to get category URL in Magento 2

categorymagento2url

In my script, I'm retrieving categories like this

$category = $this->_categoryFactory->create();
$storeCategories = $category->getCategories(1, $recursionLevel = 1, false, false, true);

$this->_storeCategories[$cacheKey] = $storeCategories;

$resultArray = [];
foreach($storeCategories as $category) {
    $arr = [];
    $arr['label'] = $category->getName();
    $arr['value'] = $category->getId();
    array_push($resultArray, $arr );
}

Then

$category->getName();

&

$category->getId();

work fine for getting category name and ID, but,

$category->getUrl();

does not work for retrieving category URL, I want to know is it a valid method call or what is the correct method get URL of the category?

Best Answer

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$obj->get('\Magento\Framework\App\State')->setAreaCode('frontend'); // for remove Area code is not set error
$objectManagerr = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManagerr->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categoryy = $categoryFactory->create()   
        ->addAttributeToSelect('*');
foreach ($categoryy as $cc)
{
    echo $cc->getId()."<br/>";
    echo $cc->getName()."<br/>";
    echo $cc->getUrl()."<br/>";
}
Related Topic