简体   繁体   中英

Disable add to cart button if product is already in WooCommerce cart

I want to disable the 'add to cart' button if the product is already added. I have managed to change the. test for an already added product so that it says 'Already added' for the button. The code or that is below. I just don't know how to disable that button in addition to that text change.

add_filter('woocommerce_product_add_to_cart_text', 'wc_product_add_to_cart_text', 10, 2 );
add_filter('woocommerce_product_single_add_to_cart_text', 'wc_product_add_to_cart_text', 10, 2 );

function wc_product_add_to_cart_text( $text, $product ){

    $product_cart_id = WC()->cart->generate_cart_id( $product->get_id() );
    $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

    if ( $in_cart ) {
        $text = "Already added";
    }
    return $text;
}

When you're editing a product in WooCommerce it's possible to select "only sold individually". I don't know if that's what you're trying to achieve, but that might be a more suitable solution and less prone to bugs.

If you are not using the default shop page at all you should put a redirect at the shop page that always redirects the user to for example the page you are using for the shop.

Besides that, here you'll find a hook you can use to disable redirects for "Add to cart".

I found this code to check if a product is already in your cart. You can get the current product id from your body_class();. Just hook this function onto woocommerce_add_to_cart.

function woo_in_cart($product_id) {
    global $woocommerce;         
    foreach($woocommerce->cart->get_cart() as $key => $val ) {
        $_product = $val['data'];

        if($product_id == $_product->id ) {
            wp_redirect( $url );
        }
    }         
}

Just add

ul.woocommerce-error {
display: none;

}

in your additional css.

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