且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

允许特定产品单独购买Woocommerce

更新时间:2021-12-17 08:47:39

假定只能从产品A购买1个数量

Assuming that only 1 quantity can be purchased from product A

function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // Product id to bought alone 
    $product_id_alone = 30;

    // Set variable
    $alone = true;

    // If passed
    if ( $passed ) {
        // If cart is NOT empty when a product is added
        if ( !WC()->cart->is_empty() ) {

            // If product id added = product id alone
            if ( $product_id_alone == $product_id ) {
                $alone = false;
            } else {
                // Generate a unique ID for the cart item
                $product_cart_id = WC()->cart->generate_cart_id( $product_id_alone );

                // Check if product is in the cart
                $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

                // If product is already in cart
                if ( $in_cart ) {
                    $alone = false;
                }
            }
        } else {
            // If product is added when cart is empty but $quantity > 1
            if ( $product_id_alone == $product_id && $quantity > 1 ) {
                $alone = false;         
            }
        }
    }

    if ( $alone == false ) {
        // Set error message
        $message = 'PRODUCT A is allow bought alone.';
        wc_add_notice( __( $message, 'woocommerce' ), 'error' );
        $passed = false;

        // Empty the cart
        WC()->cart->empty_cart();

        // Add specific product with quantity 1
        WC()->cart->add_to_cart($product_id_alone, 1 );
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );