I'm helping a friend out with some REALLY BAD magento code (which placed in a custom-made template).
In a category view I have the following code which should get simple products of a configurable product and query the simple products.
I'm not a big magento expert, but from reading, I have a feeling that looping and loading each product is a bit over-kill.
Any suggestions of how to improve the code and to read about best practices abotu querying and getting only needed data(in this case is simple products images.)
CODE:
$_productCollection=$this->getLoadedProductCollection();
$_helper = $this->helper('catalog/output');
foreach ($_productCollection as $_product):
<div class="item-product-wrap">
<?php
// Get full product object.
$conf_product = Mage::getModel('catalog/product')->load($_product->getId());
// Get all simple products.
$simple_products = $conf_product->getTypeInstance(true)->getUsedProducts(null, $conf_product);
// Get default simple product ID.
$default_simple_product_id = $conf_product->getData('default_configuration_id');
// If default simple product is not set, get the first one.
$default_simple_product_id = !$default_simple_product_id ? $simple_products[0]->getId() : $default_simple_product_id;
// Run through all simple products.
foreach ($simple_products as $simple_product):
$simple_product_loaded = Mage::getModel('catalog/product')->load($simple_product->getId());
if ($simple_product_loaded->getStatus() == 2) {
// Product is disabled.
continue;
}
// Get color. Replace spaces and ampersands with dashes to support URLs.
$color = str_replace('&', '-', str_replace(' ', '-', $simple_product->getAttributeText('color')));
// Get image.
$product_media_config_model = Mage::getModel('catalog/product_media_config');
$small_image = $product_media_config_model->getMediaUrl($simple_product->getImage());
?>
<div class="one-simple-product<?php echo ($default_simple_product_id == $simple_product->getId() ? ' active' : '') ?>">
<a href="<?php echo $_product->getProductUrl() . '#' . $color ?>" title="<?php echo $this->stripTags($this->getImageLabel($simple_product, 'small_image'), null, true) ?>" class="product-image">
<img src="<?php echo $small_image; ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($simple_product, 'small_image'), null, true) ?>" />
</a>
</div>