Magento – Magento get product collection via custom observer

ce-1.8.1.0event-observermagento-1.8product-collection

I have a custom observer in Magento 1.8.1.0 that is called on Product view page when current product having any upsell products. I have verified (using Mage::log()) that the observer is working, however when I try the following:

public function updateUpsells(Varien_Event_Observer $oObserver)
{
    $iCurrentCategory = Mage::registry('current_category')->getId();
    $oUpsellCollection = Mage::getModel('catalog/product')->getUpSellProductCollection();
    foreach ($oUpsellCollection->getItems() as $key => $oUpsellProduct) {
        $aCategoriesIds = $oUpsellProduct->getCategoryIds();
        if (!in_array($iCurrentCategory, $aCategoriesIds)) {
            $oUpsellCollection->removeItemByKey($key);
        }
    }
}

On echo $oUpsellCollection; i got nothing returned ?

Is anyone know how to get upsell products collection ? Is this a proper way to do it ?

Best Answer

Instead of using getUpSellProductCollection(), use getUpSellProducts() as it have some sort of cache. For the category validation try instead getCategoryCollection() but the getCategoryIds() method should work, make sure your product is associated to categories... and that $oUpsellProduct is instance from Mage_Catalog_Model_Product or is extended classes...