Magento: externally get relative URL's to categories


I'm building a website, and installed Magento in the /shop/ subdirectory. I'd like to integrate the top categories into the menu of my non-Magento site, so you can navigate directly into the category. For this I need the category names and url's.

Magento's categories are:

  • Templates
    • Color
    • Theme
    • General
  • Other products

I first needed to get a list of categories below the Templates top-level, so I wrote the following code. It's my first try with integrating with Magento, so be gentle :-) :

require_once dirname(__FILE__).'/shop/app/Mage.php';

$helper     = Mage::helper('catalog/category');
$collection = $helper->getStoreCategories();
foreach ($collection as $catalogArray) {
    if ($catalogArray->getName() == "Templates") {
        foreach (explode(",", $catalogArray->getChildren()) as $category) {
            $_category = Mage::getModel('catalog/category')->load($category);
            if($_category->getIsActive()) {
                $caturl = $_category->getUrl();
                $catname = $_category->getName();
            echo "<pre>";
            echo "</pre>";

            echo "<pre>";
            echo "</pre>";

This correctly gets the names and categories, but the URL's it returns are absolute full URL's, such as "".

Firstly, how do I retrieve relative URL's from Magento?

Secondly, the generated URL seems to only be correct if I set the web/unsecure/base_url setting to the If I set this to {{base_url}} instead (which we prefer during development since we use virtual-hosting based svn working copies), the /shop/ part is missing, i.e.: "".

Any idea why?

6/14/2012 5:46:20 PM

Accepted Answer

I think you can achieve all of your requirements by playing with the settings in system > configuration > web

First thing I'd try is setting base url (secure and unsecure if needed) to / (forward slash), and then going system > cache management > rebuild catalog url rewrites.

If that doesn't work, play around with the settings, bet you can get it to work. Be warned though, it will make magento put relative urls in google base feeds etc = bad! So don't do it in production.

My dev copy is at work, inacessible from here, so can't try for you.

Also, for your script above, you could try:

$url = "/shop/" . $_category->getUrlKey() . '.html';

(you may not need the html bit at the end, depends on your config)

7/11/2009 12:34:58 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow