Skip to content

Instantly share code, notes, and snippets.

@vtsara
Created May 30, 2018 22:32
Show Gist options
  • Save vtsara/4bca3327df127c568701d02a64659c1d to your computer and use it in GitHub Desktop.
Save vtsara/4bca3327df127c568701d02a64659c1d to your computer and use it in GitHub Desktop.
Renders a notice and prevents checkout if the cart contains products in certain combination of categories | woocommerce
/**
* LG :: Renders a notice and prevents checkout if the cart contains products in catering AND non-catering
*/
function lg_wc_prevent_checkout_for_category() {
// If the cart is empty, then we bail out of this function
if (WC()->cart->is_empty()) {
return;
}
// set the slug of the category for which we disallow checkout
$category = 'catering';
// 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 ( lg_woo_is_category_all_or_nothing( $category ) ) {
// if true then escape this because it's all good
return;
}
else {
// otherwise post a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'hi there! looks like your cart contains products from the %1$s and pickup categories &ndash; catering items must be ordered separately from pickup items to check out.', $category_name ), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'lg_wc_prevent_checkout_for_category' );
/**
* Checks if a cart contains exclusively products in a given category
*
* @param string $category the slug of the product category
* @return bool - true if the cart only contains the given category
*/
function lg_woo_is_category_all_or_nothing( $category ) {
// start with a count of zero
$cat_count = 0;
// loop through cart to count items that have our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( $category, 'product_cat', $cart_item['data']->get_id() ) ) {
$cat_count = $cat_count+1;
}
}
// return true if count of category = nothing or all of the items
return $cat_count === 0 || $cat_count === WC()->cart->get_cart_contents_count();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment