3

1.9.3.1 - My catalog setup is using configurable products with associated simple products. My category pages show the configurable and I'd like for the 'Add to Cart' text to read 'Only X Left' if all of the simple products for that product combined quantity is below a specific threshold. I got this working, but it puts a heavy strain on page load time whenever a cache refresh is triggered. I lazy load the category pages to begin with and this recursive manual tally of simple products multiplied by about 100 configurable products per category creates load times over 30 seconds in some cases. Is there a better method to retrieve this value (does it exist already somewhere?) and display it than how I'm accomplishing?

/app/design/frontend/mytheme/default/template/catalog/product/list.phtml

<?php $btnText = 'Add to Cart' ?>
<?php $sku = Mage::getModel('catalog/product')->load($_product->getId())->getSku(); ?>
<?php $total = 0; ?>
<?php $ids = $_product->getTypeInstance()->getUsedProductIds();  ?>
<?php foreach ($ids as $id) : ?>
    <?php $simpleproduct = Mage::getModel('catalog/product')->load($id); ?>
    <?php $total = $total + (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty(); ?>
<?php endforeach; ?>
<?php if ($total < 6) { ?>
<?php $btnText = 'Only ' . $total .' left!' ?>
<?php } ?>
  • yes, You would like to show if product inventory was 10, items ordered was 4, left was 6 you want to show 6 items in category page, it is right. – Learing_Coder Aug 9 '18 at 18:22
2

You have too many ->load() statements. This will slow down the page considerably. You should utilise product collection and get product attributes from collection item whenever possible. Change your code to something like below:

<?php $btnText = 'Add to Cart' ?>
<?php $sku = $_product->getSku(); ?>
<?php $total = 0; ?>
<?php $childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProductCollection($_product); ?>
<?php foreach ($childProducts as $childProduct) : ?>    
    <?php $total = $total + $childProduct->getStockItem()->getQty(); ?>
<?php endforeach; ?>
<?php if ($total < 6) { ?>
<?php $btnText = 'Only ' . $total .' left!' ?>
<?php } ?>
1

please Place the below code in your category page to show.

File Path:/app/design/frontend/mytheme/default/template/catalog/product/list.phtml

<?php $qty = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getStockQty(); ?>
    <?php if ($qty): ?>
        Only <?php echo $qty; ?> left
 ?> 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.