
WooCommerce:检查产品ID是否在购物车中
之前遇到过这样的一个需求:
如果购物车中有某个产品,则需要在Checkout页面中显示某些特殊的内容提示;

方法1:
function fjj_find_product_in_cart() {
$product_id = 282;
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart ) {
$notice = 'Product ID ' . $product_id . ' is in the Cart!';
wc_print_notice( $notice, 'notice' );
}
}
add_action( 'woocommerce_before_cart', 'fjj_find_product_in_cart' );方法2:
function fjj_find_product_in_cart_alt() {
$product_id = 282;
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item ) {
$product_in_cart = $cart_item['product_id'];
if ( $product_in_cart === $product_id ) $in_cart = true;
}
if ( $in_cart ) {
$notice = 'Product ID ' . $product_id . ' is in the Cart!';
wc_print_notice( $notice, 'notice' );
}
}
add_action( 'woocommerce_before_cart', 'fjj_find_product_in_cart_alt' );