限制购买特定产品

时间:2019-10-24 08:31:57

标签: woocommerce

我想限制购买某些产品。买方一次只能购买一种产品。
我使用了以下代码,但是在nicola博客中找到了,但是问题是,如果购物车中已经有其他产品,并且我添加了代码中提到的产品,那么代码就可以了。如果代码中提到的产品ID已经在购物车中,并且我添加了其他产品,则此代码将失败。

add_filter( 'woocommerce_add_to_cart_validation', 'wc_limit_one_per_order', 10, 2 );
function wc_limit_one_per_order( $passed_validation, $product_id ) {
    if ( in_array( $product_id, array( 31, 32, 33 ) ) ) {
        return $passed_validation;
    }

    if ( WC()->cart->get_cart_contents_count() >= 1 ) {
        wc_add_notice( __( 'This product cannot be purchased with other products. Please, empty your cart first and then add it again.', 'woocommerce' ), 'error' );
        return false;
    }

    return $passed_validation;
}

0 个答案:

没有答案