You need a function that you can use multiple times. This function can be used for both variable and simple products:
function ywp_check_product_is_in_cart( $product_id ) {
if ( ! WC()->cart->is_empty() ) {
foreach( WC()->cart->get_cart() as $cart_item ) {
$cart_item_ids = array( $cart_item['product_id'], $cart_item['variation_id'] );
if( in_array( $product_id, $cart_item_ids ) ) {
return true;
}
}
return false;
}
return false;
}
USAGE
add_filter( 'body_class', 'ywp_body_class_for_cart_items' );
function ywp_body_class_for_cart_items( $classes ) {
// Check user currently is in product page
if( ! is_singular( 'product' ) ) {
return $classes;
}
if( ywp_check_product_is_in_cart( get_the_id() ) ) {
$classes[] = 'already-added';
}
return $classes;
}
Code goes in functions.php
of your actiive theme/child theme. Tested and works.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…