简体   繁体   中英

How to hide add to cart button on single product page - woocommerce

I'm new to wordpress and woocommerce. I've to hide add to cart button if the product weight is greater than 8 grams. I've used this code to do so.

add_action( 'woocommerce_checkout_process', 'action_woocommerce_checkout_process', 10, 0 );

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_default_button', 10, 2 );
function replace_default_button( $button, $product ){

$weight = $product->get_weight();
preg_replace('/\D/', '', $weight);

if ( $weight > 8 ){
    $button = '';
}
return $button;
}

Its working great on shop page. But its not working on the single product page. Kindly help me to hide the add to cart button in single product page only if the product's weight is greater than 8 grams.

Your code is good for the shop page, for the single page you need to use a different hook:

// Removing the single product button add to cart
add_action( 'woocommerce_single_product_summary', 'replace_single_add_to_cart_button', 1 );
function replace_single_add_to_cart_button() {
    global $product;
    $weight = $product->get_weight();
    preg_replace('/\D/', '', $weight);

    if ( $weight > 8 ){
       // For variable product types
       remove_action( 'woocommerce_single_variation','woocommerce_single_variation_add_to_cart_button', 20 );
       // For all other product types
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM