Need Woocommerce to only allow 1 product in the ca

2019-01-08 23:18发布

I think this code should work but not exactly sure where to place it. Everywhere I have tried has failed so far...

add_action('init', 'woocommerce_clear_cart');

function woocommerce_clear_cart() {
global $woocommerce, $post, $wpdb;

$url = explode('/', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$slug=$url[4];
$postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status='publish' AND post_name = '$slug'");

    if ($postid){
        if ($postid == PRODUCTID1 || $postid == PRODUCTID2){
        $woocommerce->cart->empty_cart();
        }
    }

}

8条回答
姐就是有狂的资本
2楼-- · 2019-01-09 00:07

Based on the accepted answer and the latest Woo version 2.5.1 I updated the function to be slightly cleaner using the code woo uses in class-wc-checkout.php to clear the cart

add_filter( 'woocommerce_add_cart_item_data', '_empty_cart' );

    function _empty_cart( $cart_item_data ) {

        WC()->cart->empty_cart();

        return $cart_item_data;
    }
查看更多
别忘想泡老子
3楼-- · 2019-01-09 00:15

This worked like a charm for me, removes the previous product and adds the new one with the new product configuration. Cheers

Update: For WooCommerce 3.0.X

function check_if_cart_has_product( $valid, $product_id, $quantity ) {  

            if(!empty(WC()->cart->get_cart()) && $valid){
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];

                    if( $product_id == $_product->get_id() ) {
                        unset(WC()->cart->cart_contents[$cart_item_key]);
                    }
                }
            }

            return $valid;

        }
        add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );

For WooCommerce version less than 3.0.X

function check_if_cart_has_product( $valid, $product_id, $quantity ) {  

    if(!empty(WC()->cart->get_cart()) && $valid){
        foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
            $_product = $values['data'];

            if( $product_id == $_product->id ) {
                unset(WC()->cart->cart_contents[$cart_item_key]);
            }
        }
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
查看更多
登录 后发表回答