rocky
rocky

Reputation: 464

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?

Upvotes: 2

Views: 5013

Answers (3)

Buggenator
Buggenator

Reputation: 56

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);
}

Upvotes: 4

linus72982
linus72982

Reputation: 1393

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.

Upvotes: 0

Chris McClellan
Chris McClellan

Reputation: 1105

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;
  }
?>

Upvotes: 0

Related Questions