Replace zero or empty displayed prices with a custom text label in Woocommerce

前端 未结 1 1212
长发绾君心
长发绾君心 2021-01-16 06:03

I\'ve added this code which works for empty price fields, but I also need it to work for values of 0.

add_filter(\'woocommerce_empty_price_html\', \'custom_c         


        
相关标签:
1条回答
  • 2021-01-16 06:39

    Here is the complete way to do it for BOTH empty and zero displayed prices, so this code replace also your actual code (to be removed).

    It handle simple, variable and variation displayed prices (for BOTH empty and zero displayed prices):

    // Variable and simple product displayed prices
    add_filter( 'woocommerce_get_price_html', 'empty_and_zero_price_html', 20, 2 );
    function empty_and_zero_price_html( $price, $product ) {
        $empty_price = __('Enquire', 'woocommerce');
    
        if( $product->is_type('variable') )
        {
            $prices = $product->get_variation_prices( true );
    
            if ( empty( $prices['price'] ) ) {
                return $empty_price; // <=== HERE below for empty price
            } else {
                $min_price     = current( $prices['price'] );
                $max_price     = end( $prices['price'] );
                if ( $min_price === $max_price && 0 == $min_price ) {
                    return $empty_price; // <=== HERE for zero price
                }
                elseif ( $min_price !== $max_price && 0 == $min_price ) {
                    return wc_price( $max_price );
                }
            }
        }
        elseif( $product->is_type('simple') )
        {
            if ( '' === $product->get_price() || 0 == $product->get_price() ) {
                return $empty_price; // <=== HERE for empty and zero prices
            }
        }
        return $price;
    }
    
    // Product Variation displayed prices
    add_filter( 'woocommerce_available_variation', 'empty_and_zero_variation_prices_html', 10, 3);
    function empty_and_zero_variation_prices_html( $data, $product, $variation ) {
    
        if( '' === $variation->get_price() || 0 == $variation->get_price() )
            $data['price_html'] = __('Enquire', 'woocommerce'); // <=== HERE for empty and zero prices
    
        return $data;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    0 讨论(0)
提交回复
热议问题