Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Category image in with getChildrenCategories->getImageUrl (MAGENTO)

Tags:

php

magento

I use this $categories through out the page

$categories = Mage::getModel('catalog/category')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('level',2)
    ->addIsActiveFilter()
    ->addAttributeToSort('position'); 

foreach($categories as $cat) {$children=$cat->getChildrenCategories();}

Option 1

//option 1 

$children  = $category->getChildren();
foreach(explode(',', $children) as $child):
$sub = Mage::getModel('catalog/category')->load($child);

$sub->getName() // this return ok, name show up
$sub->getImageUrl() // this return ok, image show up

Option 2 works but can't get image url for some reason.

//option 2 
$children  = $category->getChildrenCategories();
foreach($children as $sub):

$sub->getName() // this return ok, name show up
$sub->getImageUrl() // this return empty, image NOT show up so is other attribute beside name. 

can someone explain the difference? and how would i go about it with opt 2

like image 959
aahhaa Avatar asked Feb 24 '15 19:02

aahhaa


2 Answers

Basically, When we are using getChildrenCategories() function only few fields has been retrieve from category field collection ->url_key,name,all_children,is_anchor.

you can see that on class Mage_Catalog_Model_Resource_Category.So if want tget image url from function then just add addAttributeToFilter('image')

  $collection = $category->getCollection();
$collection->addAttributeToSelect('url_key')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('all_children')
    ->addAttributeToSelect('is_anchor')
    ->setOrder('position', Varien_Db_Select::SQL_ASC)
    ->joinUrlRewrite()
->addAttributeToFilter('is_active', 1)
    ->addIdFilter($category->getChildren())
->addAttributeToSelect('image');


foreach($category as $eachChildCat){

if ($image = $eachChildCat->getImage()) {
    $url = Mage::getBaseUrl('media').'catalog/category/'.$image;
    }
}

$eachChildCat->getImage() not work then use $eachChildCat->getResource()->getImage()

like image 185
Amit Bera Avatar answered Sep 30 '22 05:09

Amit Bera


Instead of calling getModel() try to call getSingleton().

like image 37
MBM Avatar answered Sep 30 '22 06:09

MBM