Reputation: 987
Is there a way to set a specific product variation so it cant be bought without having another product in cart?
Example: I have a shop with 10 products and each with the variations "70g", "1kg" and "2kg". Now if you have "70g" variations in cart without another variation with higher value, a notice should appear and the checkout button should be disabled.
So I am looking for a way to prevent buying only variations of "70g" as those variations alone are not making profit.
I found this code to make minimum order value for cart and show a notice but I dont know how to adjust this for variations and disable buttons: https://docs.woocommerce.com/document/minimum-order-amount/
Upvotes: 0
Views: 387
Reputation: 987
I found a solution for single products by giving them a specific category. It then shows a notice when cart has products out of that category only and denies checkout:
/** Renders a notice and prevents checkout if the cart only contains products in a specific category */
function sv_wc_prevent_checkout_for_category() {
// If the cart is empty, then let's hit the ejector seat
if (WC()->cart->is_empty()) {
return;
}
// set the slug of the category for which we disallow checkout
$category = '70g';
// get the product category
$product_cat = get_term_by( 'slug', $category, 'product_cat' );
// sanity check to prevent fatals if the term doesn't exist
if ( is_wp_error( $product_cat ) ) {
return;
}
$category_name = '<a href="' . get_term_link( $category, 'product_cat' ) . '">' . $product_cat->name . '</a>';
// check if this category is the only thing in the cart
if ( sv_wc_is_category_alone_in_cart( $category ) ) {
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'Du hast ausschließlich 70g-Probierpakete in deinem Warenkorb. Aus wirtschaftlichen Gründen können wir diese nur in Kombination mit anderen Produkten anbieten. Bitte füge daher weitere Produkte zu deiner Bestellung hinzu.', $category_name ), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
/**Checks if a cart contains exclusively products in a given category*/
function sv_wc_is_category_alone_in_cart( $category ) {
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// if a product is not in our category, bail out since we know the category is not alone
if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {
return false;
}
}
// if we're here, all items in the cart are in our category
return true;
}
Upvotes: 1