Reputation: 13
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".
Upvotes: 1
Views: 1016
Reputation: 29614
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 );
Upvotes: 1