在 Woocommerce 中有条件地隐藏购物车页面优惠券字段

Hide conditionally Cart page coupon field in Woocommerce

我想隐藏所有产品的购物车页面上的优惠券字段,特定产品类别除外。我创建了以下有效的代码,但每隔一段时间似乎与时间无关,我会收到一条错误消息。它不会阻止代码运行,也不会导致任何问题。但是,我似乎无法找到我收到错误消息的原因或解决方法。

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;
}

我收到此错误消息

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-

尝试使用以下带有一些条件检查的简化代码来避免此错误问题。此外,在查看购物车项目中的产品类别时,请始终使用 $cart_item['product_id'],因为这种方式也适用于产品变体。

add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_dinner_dances' );
function hide_coupon_field_dinner_dances( $enabled ){ 
    $cart = WC()->cart; // The WC_Cart Object
    
    // Only on cart page
    if( is_cart() && $cart && method_exists( $cart, 'get_cart' ) ) {
        $category = array('discount'); // <= Here define the product categories
        $enabled  = false; // Only enable when this product category is in cart
        
        // Loop through cart items
        foreach ( $cart->get_cart() as $cart_item ) {
            if ( has_term( $category, 'product_cat', $cart_item['product_id'] ) )  {
                $enabled = true;
                break;
            }
        }
    }
    return $enabled;
}

现在应该可以更好地避免这个问题。