Get a product's parent category even if it is accessed directly

霸气de小男生 提交于 2019-12-12 16:42:49

问题


I have a custom model/block that gets the current product's parent category:

class Namespace_Module_Model_Product extends Mage_Catalog_Model_Product
{
    public function someFunction()
    {
        $category = $this->getCategory();
        ...
    }
}

This custom block is used on a product's page. This works perfectly if the product is accessed via its parent category, e.g.: domain.com/some-category/my-product.html. However, if the product is accessed directly (for example through the search) and the URL is like domain.com/my-product.html, it doesn't work. All functions from Mage_Catalog_Model_Product that could be used to retrieve the category return empty values, as if the product wasn't assigned to any categories.

My question is: What is the global way to retrieve a product's category, even if that product is not accessed via its category?


回答1:


First step: Adjust your expectation slightly — a product in Magento isn't limited to a single category. Therefore, "a global way to retrieve a product's category" should be "a global way to retrieve a list of any categories the product is in".

You'll need to to

  1. Get a reference to a product object

  2. Use that product object to get a category collection

  3. Run through the collection and pull out the category information you want

If you're on the product page, you can grab the current product from the registry.

$product = Mage::registry('product');

and then grab a category collection with

$c       = $product->getCategoryCollection()
->addAttributeToSelect('*');

The addAttributeToSelect method ensures you get all the fields you need.

Finally, you can get the individual categories themselves with

foreach($c as $category)
{
    var_dump($category->getData());
    var_dump($category->getName());
}

You could also grab the first category with

$category = $c->getFirstItem();
var_dump($category->getData());
var_dump($category->getName());


来源:https://stackoverflow.com/questions/15735324/get-a-products-parent-category-even-if-it-is-accessed-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!