Display Product Attribute Value only if it exists

Surprisingly can’t find anything on this… basically I call my custom product attributes on the product view page like this:

Men / Women: <?php echo $this->htmlEscape($_product->getmenwomen()) ?>

This displays the men/women attribute fine, but these are optional values, so if a product doesn’t have a value for this particular attribute, the line is still displayed, just with no value:

Men / Women:

I’d like that line to not show at all if there is indeed, no value for a product. Any ideas?

3 thoughts on “Display Product Attribute Value only if it exists”

  1. You have to check if the value of getmenwomen() really contains something you expect it to contain (eg men/women) before printing it. In this example i presume that anything but whitespace is a valid value.

    $menwomen = $_product->getmenwomen();
    if (trim($menwomen)) {
        echo "Men / Women: ".$this->htmlEscape($menwomen);
    }
    

  2. Not 100% on this because I am not sure if getmenwomen() will return false if its empty
    If nothing is to be returned, by default it should return false.

    <?php
      if ($var = $this->htmlEscape($_product->getmenwomen()) {
        echo "Men / Women: " + $var;
      }
    ?>
    

  3. You mean you want to display everything if there is a value and nothing if there isn’t? Just add a simple conditional:

    if (!empty($this->htmlEscape($_product->getmenwomen())))
       echo 'Men / Women: '.$this->htmlEscape($_product->getmenwomen());
    

    and that’s it, you don’t even need an else in there.

Leave a Reply

Your email address will not be published. Required fields are marked *