1

Based on the answer to How to display woocommerce sale price or regular price if there is no sale price, I have a product loop that displays the product price with a "$" sign before the price. The problem is that products without prices still show "$".

Based on the answers to Using AND/OR in if else PHP statement and wordpress/woocommerce: Remove price if zero, I tried to add an additional if condition using && but can't get it to work:

In functions.php:

function get_regular_or_sale_price() {
    global $product;
    if ( $product->price && $product->is_on_sale() ) {
        return '$'.$product->get_sale_price();
    }
    return '$'.$product->get_regular_price();
}

function get_regular_price_if_sale() {
    global $product;
    if ( $product->price && $product->is_on_sale() ) {        return '$'.$product->get_regular_price();
    }
    return '$'.$product->get_regular_price();
}

1 Answers1

2

You only need one function for this... Something like the following:

function get_regular_or_sale_price() {
    global $product;

    //First, assign the regular price to $price
    $price = $product->get_regular_price();
    if( $product->is_on_sale() ) {
        //If the product IS on sale then assign the sale price to $price (overwriting the regular price we assigned before)
        $price = $product->get_sale_price();
    }
    if ($price > 0) {
        //If the regular OR sale price (whichever is in $price at this point) is more than 0, we return the dollar sign and the price
        return '$' . $price;
    }
    //If we didn't return anything before, we do so now.  You could also return $price with no dollar sign in front, or any other string you want.
    return;
}
Kaboodleschmitt
  • 453
  • 3
  • 13