I want to hide the coupon field on the cart page for all products except for ones with a specific product category. I created the following code which works but every once in awhile which doesn't seem to be related to time, I get an error message showing up. It doesn't stop the code from working and doesn't appear to cause any issues. However, I can't seem to track down why I am getting the error message or how to solve it.
add_filter( 'woocommerce_coupons_enabled', 'wdc_hide_coupon_field_dinner_dances' );
function wdc_hide_coupon_field_dinner_dances($enabled){
$wdc_category = 'discount';
$has_cat = true;
foreach ( WC()->cart->get_cart() as $cart_item_key =>$cart_item ) {
$wdc_product = $cart_item['data'];
$product_id = method_exists( $wdc_product, 'get_id' ) ? $wdc_product->get_id() : $wdc_product->id;
if ( has_term( $wdc_category, 'product_cat', $product_id ) ) $has_cat = false;
}
if ( $has_cat && is_cart() ) {
$enabled = false;
}
return $enabled;
}
I get this error message
Error Details
=============
An error of type E_ERROR was caused in line 16 of the file /home/westviewdance/public_html/wp-content/plugins/WdcFreeTicketCoupon-for-Woocommerce/WdcFreeTicketCoupon for Woocommerce.php.
Error message: Uncaught Error: Call to a member function get_cart() on null in /home/westviewdance/public_html/wp-content/plugins/WdcFreeTicketCoupon-for-Woocommerce/WdcFreeTicketCoupon
for Woocommerce.php:16 Stack trace:
#0 /home/westviewdance/public_html/wp-includes/class-wp-hook.php(287): wdc_hide_coupon_field_dinner_dances(true)
#1 /home/westviewdance/public_html/wp-includes/plugin.php(206): WP_Hook->apply_filters(true, Array)
#2 /home/westviewdance/public_html/wp-content/plugins/woocommerce/includes/wc-coupon-functions.php(69): apply_filters('woocommerce_cou...', true)
#3 /home/westviewdance/public_html/wp-content/plugins/woocommerce/packages/woocommerce-blocks/src/Assets.php(157): wc_coupons_enabled()
#4 /home/westviewdance/public_html/wp-includes/class-wp-hook.php(287): Automattic\WooCommerce\Blocks\Assets::get_wc_block_data(Array)
#5 /home/westviewdance/public_html/wp-includes/plugin.php(206): WP_Hook->apply_filters(Array, Array)
#6 /home/westviewdance/public_html/wp-content/plugins/woocommerce/packages/woocommerce-