Skip to content

Instantly share code, notes, and snippets.

@Garconis
Created October 10, 2017 12:21
Show Gist options
  • Save Garconis/96a7610c6e20c640047d97ca749e32eb to your computer and use it in GitHub Desktop.
Save Garconis/96a7610c6e20c640047d97ca749e32eb to your computer and use it in GitHub Desktop.
WooCommerce | Check if Product Category is in the Cart
<?php
/**
* Check if Product Category is in the Cart - WooCommerce
* https://businessbloomer.com/?p=72900
*/
add_action('woocommerce_before_cart', 'fs_check_category_in_cart');
function fs_check_category_in_cart() {
// Set $cat_in_cart to false
$cat_in_cart = false;
// Loop through all products in the Cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// If Cart has category "download", set $cat_in_cart to true
if ( has_term( 'download', 'product_cat', $product->get_id() ) ) {
$cat_in_cart = true;
break;
}
}
// Do something if category "download" is in the Cart
if ( $cat_in_cart ) {
// For example, print a notice
wc_print_notice( 'Category Downloads is in the Cart!', 'notice' );
// Or maybe run your own function...
// ..........
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment