Why is getUrlPath($category) Not Including the Product’s URL Key in Magento 1.7?

magento-1.7

Calling getUrlPath($category) on a product isn't including the product's url key / suffix?

E.g. it will return /category_name/subcategory_name while I am expecting /category_name/subcategory_name/product_name

From the docs I've read getUrlPath should include everything after the base URL. If this is not the case, what is the best way to get the full URL for a product while providing the category?

Here is a simple test case code-wise:

$product = Mage::getModel('catalog/product')->load(123);
$category = Mage::getModel('catalog/category')->load(456);

echo $product->getUrlPath($category);

Product ID 123's url key is 'test-product'.
Category ID 456's url key is 'subcat1', and it is a child of 'cat1'.

There are no suffixes on category or product pages.

The expected output would be /cat1/subcat1/test-product. The actual output is /cat1/subcat1/.

I have seen many examples where getUrlPath includes the product's URL key (test-product) and from my understanding it should. If this is not the case, how can I get what I am looking for. I did consider pulling the URL key directly (also tried a slightly hacked together option – basename($product->getProductUrl()), but the url key can be changed between categories by URL rewrites when there are conflicts.

Best Answer

Product->getUrlPath calls ProductUrl->getUrlPath in /core/Mage/Catalog/Model/Product/Url.php. I've quoted the function below, as you can see it concatenates the category->getUrlPath with product->getData('url_path'). I'd check that url_path is set properly on your product.

 /**
 * Retrieve Product Url path (with category if exists)
 *
 * @param Mage_Catalog_Model_Product $product
 * @param Mage_Catalog_Model_Category $category
 *
 * @return string
 */
public function getUrlPath($product, $category=null)
{
    $path = $product->getData('url_path');

    if (is_null($category)) {
        /** @todo get default category */
        return $path;
    } elseif (!$category instanceof Mage_Catalog_Model_Category) {
        Mage::throwException('Invalid category object supplied');
    }

    return Mage::helper('catalog/category')->getCategoryUrlPath($category->getUrlPath())
        . '/' . $path;
}
Related Topic