Last active
June 23, 2017 04:25
-
-
Save WPprodigy/872e30c8711a37988a6570d7b1675762 to your computer and use it in GitHub Desktop.
WooCommerce: Add notices to the cart/checkout page when specific categories are together in the cart.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Hook in to add notices to the cart and checkout pages | |
add_action( 'woocommerce_before_cart_contents', 'wc_ninja_add_cart_notice' ); | |
add_action( 'woocommerce_before_checkout_form', 'wc_ninja_add_cart_notice' ); | |
/** | |
* Add the cart/checkout notice | |
*/ | |
function wc_ninja_add_cart_notice() { | |
$message = "Sorry, you cannot purchase products from the clothing and music category together."; | |
// Exchange "clothing" and "music" for your own categories. | |
if ( wc_ninja_categories_in_cart( array( 'clothing', 'music' ) ) ) { | |
echo '<div id="woocommerce-cart-notice-gateways-unavailable" class="woocommerce-cart-notice woocommerce-error">' . $message. '</div>'; | |
} | |
} | |
/** | |
* Check if specific product categories are in the cart. | |
* | |
* @param array $categories | |
*/ | |
function wc_ninja_categories_in_cart( $categories ) { | |
// Products currently in the cart | |
$cart_ids = array(); | |
// Categories currently in the cart | |
$cart_categories = array(); | |
// Find each product in the cart and add it to the $cart_ids array | |
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) { | |
$cart_product = $values['data']; | |
$cart_ids[] = $cart_product->id; | |
} | |
// Connect the products in the cart w/ their categories | |
foreach( $cart_ids as $id ) { | |
$products_categories = get_the_terms( $id, 'product_cat' ); | |
// Loop through each product category and add it to our $cart_categories array | |
foreach ( $products_categories as $products_category ) { | |
$cart_categories[] = $products_category->slug; | |
} | |
} | |
// If all of the special categories are in the cart, return true. | |
if ( ! array_diff( $categories, $cart_categories ) ) { | |
return true; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment