WooCommerce if 条件(如果产品在购物车中做某事)

WooCommerce if condition (if product is in cart do something)

我正在尝试在 WooCommerce 购物车页面上显示附加按钮 [预约],该按钮会将用户带到包含产品的页面以进行预约。这部分效果很好。我还尝试检查产品 ID 444908 是否已在购物车中。产品 ID 444908 是预约产品,如果有人已经预约,则不应显示该按钮,因为该人已经在购物车中预约了产品。 似乎问题出在我的 IF 条件上。当我使用它时,无论产品 444908 是否在购物车中,它都不会显示按钮。

我做错了什么?

add_action( 'woocommerce_after_cart_totals', 'my_continue_shopping_button' );
function my_continue_shopping_button() {
    $product_id = 444908;
    $product_cart_id = WC()->cart->generate_cart_id( $product_id );
    $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
    if ( $in_cart ) {
 echo '<div class="bookbtn"><br/>';
 echo ' <a href="/book-appointment/" class="button"><i class="fas fa-calendar-alt"></i> Book Your Appointment</a>';
 echo '</div>';
 }
}

find_product_in_cart returns 如果未找到产品,则为空字符串 所以你需要

 if ( $in_cart !="" ) 

info

最后我使用了外部函数:

function woo_is_in_cart($product_id) {
    global $woocommerce;
    foreach($woocommerce->cart->get_cart() as $key => $val ) {
        $_product = $val['data'];
        if($product_id == $_product->get_id() ) {
            return true;
        }
    }
    return false;
}

然后我用这个检查产品是否在购物车中:

if(woo_is_in_cart(5555) !=1) {
/* where 5555 is product ID */

这是我用了一段时间的东西

function is_in_cart( $ids ) {
    // Initialise
    $found = false;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // For an array of product IDs
        if( is_array($ids) && ( in_array( $cart_item['product_id'], $ids ) || in_array( $cart_item['variation_id'], $ids ) ) ){
            $found = true;
            break;
        }
        // For a unique product ID (integer or string value)
        elseif( ! is_array($ids) && ( $ids == $cart_item['product_id'] || $ids == $cart_item['variation_id'] ) ){
            $found = true;
            break;
        }
    }

    return $found;
}

对于单个产品 ID:

if(is_in_cart($product_id)) {
    // do something
}

对于 product/variation 个 ID 数组:

if(is_in_cart(array(123,456,789))) {
    // do something
}

...或者...

if(is_in_cart($product_ids)) {
    // do something
}