Php 如果未设置价格,则删除价格

Php 如果未设置价格,则删除价格,php,function,if-statement,woocommerce,Php,Function,If Statement,Woocommerce,根据对的回答,我有一个产品循环,它显示产品价格,价格前有一个“$”符号。问题是,没有价格的产品仍然显示“$” 根据和的答案,我尝试使用&&添加一个附加的if条件,但无法使其工作: 在functions.php中: function get_regular_or_sale_price() { global $product; if ( $product->price && $product->is_on_sale() ) { return

根据对的回答,我有一个产品循环,它显示产品价格,价格前有一个“$”符号。问题是,没有价格的产品仍然显示“$”

根据和的答案,我尝试使用
&&
添加一个附加的if条件,但无法使其工作:

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

你只需要一个函数就可以了。。。如下所示:

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