Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm working on a products showcase website, and in my index I have this snippet of code for my two variables ($price for the price, $buynow for the URL)

<div class="buyitnow">
<?php global $post; $price = get_post_meta($post->ID, 'price', true);
$buylink = get_post_meta($post->ID, 'buynow', true);
if ( $price ) { ?>$<?php echo ( number_format($price, 2, ".", "") * 100 / 100 ); 
Echo "(<a href=$buylink>Buy</a>)" ?>
<?php } else {} ?></div>

This works perfectly. For a non-product post, when no price is filled, nothing is displayed.

However, there are products that the price of is TBA (To Be Announced). I suspect because I'm using number_format when I enter TBA as the value of price it automatically outputs $0.

How can this be fixed while taking into account that I do need to use number_format so I can sort products by price later on.

Please note that I'm just starting to get my hands dirty with code so any further elaboration will be much appreciated!

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

The problem is that you're trying to perform a math operation on a string ('TBA') so the result is going to be 0. Try testing if the value is numeric by using the php function is_numeric(). You can see the docs for that function here.

So in your code do this:

if (is_numeric($price)) {

    ...format the number

} else {

   echo 'TBA';

}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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