Magento 1.6 – Echo Div on list.phtml if Product Has Custom Options

custom-optionslist.phtmlmagento-1.6php-5.4

I'm fairly new to Magento and looking at PHP code is just daunting to me so I'm trying to learn by doing.
I've been looking into making my own "Free Gift" label for items on my store but no extension I've found is able to give me the specific functionality I require. Basically if the product has an option with the label "Free Gift" then echo out my .

I managed to get some code that does this perfectly except it displays the Free Gift label on any product that has an option available (size for example).

<?php if ( $_product->getData('has_options') && ($_product->getTypeID() == 'simple') ): ?>
<div class="free_gift_text"><?php echo "Free Gift" ?></div>; 
<?php endif; ?>

If I place this code in my theme files (media.phmtl, list.phtml) then it works like I want it to except with the problem above (as the code only looks for if the product has options)

Now below I have some different code that works PERFECTLY on the product pages.

<?php

$theoptions = $_product->getOptions();
foreach($theoptions as $opkey=> $opval)

if(( $_product->getData('has_options')) && ($_product->getTypeID() == 'simple') && ($opval->getTitle() == 'Free Gift')): ?>
   <div class="free_gift_text"><?php echo "Free Gift" ?></div>;
<?php endif; ?> 

But it doesn't work when I place it in list.phtml, no labels show up at all. I'm not sure why this is but I think it's because it can't read if the products had options or not.

I'm not sure if I'm going the wrong way about this or if there's a different solution to this but any help would be massively appreciated as I'm not very experienced in PHP, Thank you.

Best Answer

On listing page you cant get product custom option directly,,for that you have to load $_product object

write below code in your list.phtml

<?php foreach ($_productCollection as $_product): ?>

<?php $product = Mage::getModel("catalog/product")->load($_product->getId()); ?>

and then write your logic

    <?php 
$theoptions = $product->getOptions();
foreach($theoptions as $opkey=> $opval)
{
    if(( $product->getData('has_options')) && ($product->getTypeID() == 'simple') && ($opval->getTitle() == 'Free Gift')): ?>
       <div class="free_gift_text"><?php echo "Free Gift" ?></div>;
    <?php endif; ?>   
}
?>

Note::It may down your web speed perfomance on listing page because it every time load product object

Related Topic