1
votes

I've been trying to modify Display price on add to cart button from the functions.php file in WooCommerce so it displays a price on the "Add to cart" button (in Wordpress) but only if the price is higher than zero.

Unfortunately I'm stuck. When the price is zero or not set at all the button still displays "Add to cart - 0.00 USD". I just need "Add to cart".

1
Please always mention the source if you are using existing code, I assumed that you had written / modified this code yourself and that is not the case. Also include what you have tried so far. Please read How do I ask a good question? and Stack Overflow question checklist.7uc1f3r

1 Answers

1
votes

Note the extra if conditions who check the price. Explanation via comment tags added in the code

function custom_add_to_cart_price( $button_text, $product ) {
    // Product type = variable
    if ( $product->is_type('variable') ) {
        
        // NOT return true when viewing a single product.
        if( ! is_product() ) {
            // Get price
            $price = wc_get_price_to_display( $product, array( 'price' => $product->get_variation_price() ) );
            
            // Greater than
            if ( $price > 0 ) {
                $product_price = wc_price( $price );
                $button_text .= ' - From ' . strip_tags( $product_price );  
            }
        }
    } else {
        // Get price
        $price = wc_get_price_to_display( $product );
        
        // Greater than
        if ( $price > 0 ) {
            $product_price = wc_price( $price );
            $button_text .= ' - Just ' . strip_tags( $product_price );
        }
    }
    
    return $button_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 10, 2 );