i use this code to assign a image to a drop product attribute named stock_status (a dropdown att):

<?php $_stockStatus = $_product->getAttributeText('stock_status'); ?><img src="/media/atticons/<?php echo $_stockStatus; ?>.png">

every thing is allright .but in product pages which are not connected to this attribute or do not have any value of this attribute, a broken image with this location address will shown: mysite.com/media/atticons/.png. how to remove this image from product pages which are not connected to stock_status attribute?

  • if($_product->getAttributeText('stock_status')): //do something endif; – Ahmed Elawadi Mar 3 '15 at 14:50

Easy option:

        //do something


<?php if($_stockStatus = $_product->getAttributeText('stock_status')): ?>
    <img src="/media/atticons/<?php echo $_stockStatus ?>.png">
<?php endif; ?>


Above will not work if you have space in the attribute, so you could do this:

<?php if($_stockStatus = $_product->getAttributeText('stock_status')): ?>
          $_stockStatus = $_product->getAttributeText('stock_status'); // get value .
          $_stockStatus = preg_replace("/[^a-zA-Z]+/", "-", $_stockStatus); // replace space with _ .
          $_stockStatus  = strtolower($_stockStatus ); // change to lower cases .
       <img src="/media/atticons/<?php echo $_stockStatus ?>.png">
    <?php endif; ?>
  • im new in magento. can you apply my code in yours pleas? – Moh3n Mar 3 '15 at 15:12
  • I did please see the answer again – Ahmed Elawadi Mar 3 '15 at 15:32
  • your second code won't work. but first one works like a charm! – Moh3n Mar 3 '15 at 15:48
  • why it didn't work, what was the error? glade to help anyway – Ahmed Elawadi Mar 3 '15 at 15:50
  • no error just won't show any thing in frontend. i should mention that my image name is not in english. – Moh3n Mar 3 '15 at 15:52

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.