0
votes

I am using WooCommerce and WooCommerce Brands which creates the taxonomy "product_brand".

I need to restrict the cart so that a customer can only purchase products from single "Brand", if they try to enter products from another brand into their cart it should display a message stating something like:

Products from multiple brands cannot be included within the same cart. (Button - "Clear Cart & Add")

It would be great if a button could also be added that allows the customer to "Clear Cart & Add" the product they were attempting to purchase.

1
You are expected to provide your real own code attempt. Please note that StackOverFlow is not a free coding service.LoicTheAztec

1 Answers

0
votes

To achieve this copy / paste the custom function below into your child theme functions.php or use the plugin called, Code Snippets.

add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation_callback', 10, 3 );
function add_to_cart_validation_callback( $passed, $product_id, $quantity) {
    // HERE set your alert text message
    $message = __( 'Unable to add to cart: You may only checkout with one club at a time.', 'woocommerce' );

    if( ! WC()->cart->is_empty() ) {
        // Get the product brand terms for the current product
        $terms_slugs = wp_get_post_terms( $product_id, 'product_brand', array('fields' => 'slugs'));

        // Loop through cart items
        foreach (WC()->cart->get_cart() as $cart_item ){
            if( ! has_term( $terms_slugs, 'product_brand', $cart_item['product_id'] )) {
                $passed = false;
                wc_add_notice( $message, 'error' );
                break;
            }
        }
    }
    return $passed;
}