0

I am using the following to get the complete product data from the observer:

$product = $observer->getProduct()->getData();

But I could not notice any information about the category of the product.

How can I get the data about the product category, such as category id from the observer?

  • What event do you using? – Prasanta Hatui Jun 12 '17 at 8:10
  • I am using the event catalog_controller_product_view – anthony Jun 12 '17 at 8:12
1

You can use this in your observer:

public function yourMethod(Varien_Event_Observer $observer)
{
    $categoryId = '';
    if ($category = Mage::registry('current_category')) {
        $categoryId = $category->getId();
    }
}

Edit:

Okay first of all why the if statement is needed? Second I tried the code updated and previous and still nothing. When I keep the if statement it returns null and without the if statement it gives the error: Call to a member function getId() on null.

The if-statement is required to check if you view a product within a category. Products can also be viewed without category path ... if $categoryId returns null you are not in a category. Please check URL for the viewed product.

  • I tried adding $category = Mage::registry('current_category') and $categoryId = $category->getId() but this gave me an error: Call to a member function getId() on null . – anthony Jun 12 '17 at 9:01
  • Have you used the code as posted? Including if ($category ...? Updated answer ... – sv3n Jun 12 '17 at 9:05
  • Okay first of all why the if statement is needed? Second I tried the code updated and previous and still nothing. When I keep the if statement it returns null and without the if statement it gives the error: Call to a member function getId() on null. – anthony Jun 12 '17 at 9:08
  • $category = Mage::registry('current_category'); with var_dump gives null as well. – anthony Jun 12 '17 at 9:11
  • Then you are not in a category ... updated answer for better readablity – sv3n Jun 12 '17 at 9:16
0

Try this:

$product = $observer->getProduct();
$catIds = $product->getCategoryIds();
//var_dump($catIds);
  • This works as it gives me the id of the category. But is there any way to get the id from $product = $observer->getProduct()->getData()? I need this getData() to get the complete product data. Or should I retrieve the category individually from the rest of the product data? – anthony Jun 12 '17 at 9:03
  • Magento do not give category Ids with getData method as category ids assigned different array to product object. – Prasanta Hatui Jun 12 '17 at 9:28
  • @PrasantaHatui could you pls help me with my post -> magento.stackexchange.com/q/284557/57334 – zus Aug 7 at 11:43

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.