简体   繁体   中英

Magento: Displaying all categories but cannot get associating images

I am having a odd but probably easily solvable situation.

I have the following code in a block:

<div class="home-categories">
    <?php $_helper = Mage::helper('catalog/category') ?>
    <?php $_categories = $_helper->getStoreCategories() ?>
    <?php foreach($_categories as $_category): ?>
        <a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
            <img src="<?php echo $_category->getStoreIds(); ?>"/>
            <div class="category-title">
                <p><?php echo $_category->getName(); ?></p>
            </div>
        </a>
      <?php endforeach; ?>
</div>

The resulting HTML I get returns me all the correct details but the img src. I am doing this correctly ?

The reason you you're not getting the image url is because, by default, Magento models do not come loaded with all of the attributes. This is so you only load attributes you need and your DB queries aren't as expensive. The following will do the trick.

$_helper = Mage::helper('catalog/category');
$_categories = $_helper->getStoreCategories(false, true, false);
$_categories->addAttributeToSelect('image');

Take aa look at the method definition for getStoreCategories:

getStoreCategories($sorted=false, $asCollection=false, $toLoad=true)

You want the method to return a collection that hasn't been loaded yet, thus the false, true, false arguments. Before you loop through the categories you want to make sure the image attribute is loaded as well, this is what the addAttributeToSelect('image') call is for.

This was is more efficient than $_category->load( $_category->getId()); because we are not loading the entire entity. Now when you loop through the categories you can do the following and you should have the image URL in the image tag.

<img src="<?php echo $_category->getImageUrl(); ?>"/>

The reason is that the loaded categories collection doesn't contain category attributes but only basic category data. You have to load them yourself or add them to the collection before it gets loaded (didn't take a look at the helper function so I can't be certain if you could do that after the call to it...).

The simplest solution is to replace line

<img src="<?php echo $_category->getStoreIds(); ?>"/>

with

<img src="<?php $_category->load( $_category->getId()); echo  $_category->getImageUrl(); ?>"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM