marchemike marchemike - 1 month ago 40
PHP Question

Get category URL key in Magento

How do I get the URL key of a category in Magento. I have added this text in URL key field the CMS:

Category-1


This is how I'm currently trying to show my category URL in an anchor:

$_categories = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('is_active');

<?php foreach($_categories as $_category): ?>
<a href="<?php echo $_category->getCategoryUrl($_category); ?>">
<?php endforeach; ?>


But whenever I check my output it still shows like this:

<a href="">
<span>Manual Tile Cutters</span>
</a>


I have already checked google and the magento forums for this, but I still cannot find a sufficient answer.

Also, is what I'm trying to call in the anchor the URL key, or is it a different URL?

Ron Ron
Answer

Both other answers there is a DB penalty. Best way to add Category URL info is at the collection level and simply use it to your liking in your template files. Adjust your code as follows:

    $_categories = Mage::getModel('catalog/category')->getCollection()
                     ->addAttributeToSelect('name')
                     ->addAttributeToSelect('is_active')
                     ->addUrlRewriteToResult();

<?php foreach($_categories as $_category): ?>
<a href="<?php echo $_category->getUrl($_category); ?>">
  <?php endforeach; ?>

Notice the additional method applied to the Category Collection called addUrlRewriteToResult() and call the url by using the getUrl() instead of what you had before which was getCategoryUrl() (no such thing in the code).

By the way, your code should work just fine if you call getUrl() but will impact performance slightly.

I hope this helps.