Get a product's parent category even if it is

2019-07-09 19:42发布

问题:

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());