2

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.

  • 1
    Can you please post the full code that you are using? – Marius Oct 31 '13 at 7:34
  • I added a testcase and a bit more detailed of an explanation. Let me know if that doesn't quite clear it up. – Matt Dunbar Oct 31 '13 at 8:12
9

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;
}

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.