在继续进行结帐/下订单之前,我需要强制将WC优惠券(作为产品出售)应用于其他特定产品(或类别)。在这种情况下,优惠券(使用Woo-commerce Smart Coupon插件)作为“信息积分”出售,必须用于发送在线消息(每个优惠券10条消息)。发送在线消息(电子卡)是只能使用消息积分(应用优惠券)购买的产品。还有其他我完全不想使用优惠券的服务。
我在下面关于堆栈溢出的另一篇文章中找到了下面显示的代码,并使用代码片段插件将其添加到主题函数文件中。我更改了类别数组中的值,以匹配我要强制使用优惠券的产品的类别。 但是它使第18行中的错误导致站点崩溃:未捕获的错误:在中的null上调用成员函数get_applied_coupons()。 。
// Force Coupon codes for Woocommerce
add_action('woocommerce_check_cart_items', 'mandatory_coupon_code');
function mandatory_coupon_code()
{
// set Here your categories IDs, slugs or names
$categories = array(18,19,87);
$found = false;
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item )
if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
// Product category found in cart items
$found = true;
// Exit from loop
break;
}
}
$coupons = WC()->cart->get_applied_coupons();
// The Notice is displayed for that product categories when no mandatory coupon has been entered
if( count( $coupons ) > 0 && $found )
wc_add_notice( __( 'A coupon code is mandatory for this product.', 'woocommerce' ), 'error' );
我正在使用最新的Woo-commerce和WordPress。