I’m building an online store with wordpress and woocommerce. I need to replace the add to cart button with a new button if the product’s weight is greater than 10 gram. how can I to do so?
Advertisement
Answer
I have a solution for replacing add to cart button for particular WooCommerce products(based on weight). so, you can use the below code and put it in the functions.php
JavaScript
x
// To change add to cart text on single product page
add_filter( 'woocommerce_product_single_add_to_cart_text',
'woocommerce_custom_single_add_to_cart_text' );
function woocommerce_custom_single_add_to_cart_text() {
global $product;
$weight = $product->get_weight();
preg_replace('/D/', '', $weight);
if ( $product->has_weight() && ($weight > '9') ) {
return __( 'Custom text', 'text-domain' );
}
return __( 'Add to Cart', 'text-domain' );
}
// To change add to cart text on product archives(Collection) page
add_filter( 'woocommerce_product_add_to_cart_text',
'woocommerce_custom_product_add_to_cart_text' );
function woocommerce_custom_product_add_to_cart_text() {
global $product;
$weight = $product->get_weight();
preg_replace('/D/', '', $weight);
if ( $product->has_weight() && ($weight > '9')) {
return __( 'Custom text', 'text-domain' );
}
return __( 'Add to Cart', 'text-domain' );
}