We have listed some of our popular functions that we use again and again. We will be adding more functions in the future so keep an eye out. I hope that these functions will be useful for your development with Magento and save you some time.

Get all current categories

Here is a basic function that returns all Magento current categories, it returns a list of categories ordered from children to parents. Because it returns both the id’s of the categories and the object it allows for more flexibility. The while loop has a fail-safe of 15 iterations should the while loop go into a infinite loop.

/*
 * Get current categories
 */
public function get_current_categories() {

	$oCurrentCat = Mage::registry('current_category');
	if(!$oCurrentCat) {
		return false;
	}
	
	$iRootCategory	= Mage::app()->getStore()->getRootCategoryId();	
	$oCategories	= array(0 => $oCurrentCat);
	$aIds			= array(0 => $oCurrentCat->getId());
	
	//Amount of iterations before script gives up
	$iLastIt	= 15;
	
	if($oCurrentCat) {
		
		// Quick see if the current category is a model
		if(!($oCurrentCat instanceof Mage_Catalog_Model_Category) ) {
			return false;
		}
		
		// Loop until there are no parent categories or root category has been 
		// reached. Or that the iteration limit has been reached
		while($oCurrentCat->getLevel() != $iRootCategory && --$iLastIt > 0) {
			
			// Break once no category found
			if(!($oCurrentCat instanceof Mage_Catalog_Model_Category)) {
				break;
			}
			
			// Add category id and model to returned array
			$oCurrentCat	= $oCurrentCat->getParentCategory();
			$oCategories[]	= $oCurrentCat;
			$aIds[]			= $oCurrentCat->getId();

		}

		if($oCurrentCat) {
			return array('ids' => $aIds, 'obj' => $oCategories);
		} else {
			return false;
		}
	}
	
	return false;
	
}
List all subcategories from current category

Pass the function a category id and it will return a object array.

/*
 * Display list by Sub Categories
 */
public function get_sub_cats( $iCategoryId = 0 ) {
	
	// Load category, if not exist return
	$oCategory = Mage::getModel('catalog/category')->load( (int) $iCategoryId);
	if(!$oCategory->getId()) {
		return false;
	}
	
	// Get category sub cats
	$aSubcats 		= $oCategory->getChildrenCategories();
	$aCategories 	= array();
	$aIds			= array();	

	if(count($aSubcats) > 0) {
		foreach($aSubcats as $oSubCat) {
			$aCategories[]	= $oSubCat;
			$aIds[]			= $oSubCat->getId();
		}
		return array('obj' => $aCategories, 'ids' => $aIds);
	}
	return false;
	
}