2

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?

1
<?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/>";
}
0

If your phtml class is \Magento\Catalog\Block\Category\View

Then you can get full url by using $block->getCategoryUrl($category)

-2

Get Category URL From Category ID Using below code :

For Category url :

$categoryId = 3;

$categoryObj = $this->categoryRepository->get($categoryId);

echo  $this->categoryHelper->getCategoryUrl($categoryObj);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.