0

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!

1 Answer 1

3

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';

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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