当我在卡片中有这两个不同类别的产品时,我试图设置通知WooCommerce
.
这是我使用的代码:
add_action( \'woocommerce_checkout_before_customer_details\', \'webroom_check_if_product_category_is_in_cart\' );
function webroom_check_if_product_category_is_in_cart() {
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( \'cat1\', \'product_cat\', $cart_item[\'product_id\'] ) &&
has_term( \'cat2\', \'product_cat\', $cart_item[\'product_id\'] ) ) {
$cat_in_cart = true;
break;
}
}
if ( $cat_in_cart ) {
$notice = \'Notification\';
wc_print_notice($notice, \'notice\');
}
}
如果我只设置了一个类别,那么这段代码就可以完美地工作,但是当我设置了两个类别时,由于某种原因,我既没有结果也没有错误。
最合适的回答,由SO网友:Sam 整理而成
我很快想到了这一点:
(但这并不是我的最佳选择!也许我有时会来重写一段更为深思熟虑的代码,但现在,这段代码可以正常工作了)
add_action( \'woocommerce_before_cart\', \'webroom_check_if_product_category_is_in_cart\' );
function webroom_check_if_product_category_is_in_cart() {
$cat1_in_cart = false;
$cat2_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( \'cat1\', \'product_cat\', $cart_item[\'product_id\'] ) ) {
$cat1_in_cart = true;
} elseif(has_term( \'cat2\', \'product_cat\', $cart_item[\'product_id\'] )){
$cat2_in_cart = true;
}
}
if ($cat1_in_cart === true && $cat2_in_cart === true) {
$notice = \'Notification\';
wc_print_notice($notice, \'notice\');
}
}
SO网友:batman
以下是解决方案:
add_action( \'woocommerce_before_cart\', \'webroom_check_if_product_category_is_in_cart\' );
function webroom_check_if_product_category_is_in_cart() {
$cat1_in_cart = false;
$cat2_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( \'cat1\', \'product_cat\', $cart_item[\'product_id\'] ) ) {
$cat1_in_cart = true;
} elseif(has_term( \'cat2\', \'product_cat\', $cart_item[\'product_id\'] )){
$cat2_in_cart = true;
}
}
if ($cat1_in_cart === true && $cat2_in_cart === true) {
$notice = \'Notification\';
wc_print_notice($notice, \'notice\');
}
}