如果产品变体已添加到购物车,则移除块

Remove the block if the product variation was already added to cart

我的 functions.php 文件中的以下代码允许我在结帐页面上添加一个块。如果购物车包含 ID 为 "100" 且变体 "111" 的产品,则此块建议添加具有变体 ID 100 且变体 112 的产品。 如果用户单击此按钮并将 ID 为 100、变体为 112 的产品添加到他的购物车,我该如何删除 ID="u-1" 块?

add_action('woocommerce_review_order_before_submit', 'displays_cart_products_feature_image');
function displays_cart_products_feature_image() {
    // set your products IDs here:
    $product_ids = array(100);
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) && ($cart_item['variation_id'] == 111) )
                    $bool = true;
    }
    // If the special cat is detected in one items of the cart
    // It displays the message
    if ($bool)
        echo '
        <div id="u-1">
            <a href="/?add-to-cart=100&variation_id=112">Add new item</a>
        </div>';
}

我知道如何在使用 javascript 单击按钮后隐藏块,但有一个问题:将具有 ID "100" 和变体 112 的产品添加到购物车后,页面重新加载并且块再次可见。所以我想用 PHP 来实现这个,但我仍然不知道如何实现。

如果变体 ID 已在您的购物车中,只需设置 $bool = false

add_action('woocommerce_review_order_before_submit', 'displays_cart_products_feature_image');
function displays_cart_products_feature_image() {
    // set your products IDs here:
    $product_ids = array(100);
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) && ($cart_item['variation_id'] == 111) )
                    $bool = true;
    }
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) && ($cart_item['variation_id'] == 112) )
                    $bool = false;
    }
    // If the special cat is detected in one items of the cart
    // It displays the message
    if ($bool)
        echo '
        <div id="u-1">
            <a href="/?add-to-cart=100&variation_id=112">Add new item</a>
        </div>';
}