在 woocommerce 中,我尝试使用以下方法检查特定产品类别的购物车项目:
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'];
echo '<pre>',print_r($product),'</pre>';
// If Cart has category "download", set $cat_in_cart to true
if ( has_term( 'downloads', 'product_cat', $product->get_id() ) ) {
$cat_in_cart = true;
break;
}
}
// Do something if category "download" is in the Cart
if ( $cat_in_cart ) {
// For …Run Code Online (Sandbox Code Playgroud)