获取购物车中物品的ID可以这样做:
global $woocommerce;
$cart = $woocommerce->cart->get_cart();
$cart_items_ids = array();
foreach ( $cart as $item_key => $item_value ) {
$cart_items_ids[] = $item_value[ \'data\' ]->id;
}
或者请检查下面的代码片段:检查购物车中是否有产品类别–WooCommerce
add_action(\'woocommerce_before_cart\', \'xyz_check_category_in_cart\');
function xyz_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\'];
// If Cart has category "download", set $cat_in_cart to true
if ( has_term( \'download\', \'product_cat\', $product->get_id() ) ) {
$cat_in_cart = true;
break;
}
}
// Do something if category "download" is in the Cart
if ( $cat_in_cart ) {
// For example, print a notice
wc_print_notice( \'Category Downloads is in the Cart!\', \'notice\' );
// Or maybe run your own function...
}
}
您可以将PHP代码片段放在子主题函数的底部。php文件(如果有的话,请在“?>”之前)。
如果一切按预期进行,请在评论中告诉我。
非常感谢。