Retrieve a list of all parent category url keys in Magento

In this example, we only want to show a block for a product which resides within a particular category. We check all of the category’s parent categories and show the block if any of them match our $_allowedCategories array. Using URL keys instead of category IDs makes this code more portable between environments such as development and production where IDs may not be the same.

<?php
class Namespace_Module_Block_Catalog_Product_Request_Form extends Mage_Core_Block_Text_List
{
    protected $_allowedCateogies = array('shelters');

    protected function _toHtml()
    {
        $allCatUrls = array();

        // get an array of all parent category url keys
        if($product = Mage::registry('current_product')){
            $cats = $product->getCategoryCollection()->addAttributeToSelect('url_key');

            foreach($cats as $cat){
                $this->_getParentUrlKeys($cat, $allCatUrls);
            }
        }

        // Check whether the category is in the array
        foreach($this->_allowedCateogies as $category){
            if(in_array($category, $allCatUrls)){
                return parent::_toHtml();
            }
        }

        return '';
    }

    // Recursively get all of the parents url keys
    protected function _getParentUrlKeys(Mage_Catalog_Model_Category $cat, &$urlKeys)
    {
        if(!in_array($cat->getUrlKey(), $urlKeys)) {
            $urlKeys[] = $cat->getUrlKey();
        }

        if($cat->getParentCategory()->getId()){
            return $this->_getParentUrlKeys($cat->getParentCategory(), $urlKeys);
        }
    }
}