Home > Net >  Remove the block if the product variation was already added to cart
Remove the block if the product variation was already added to cart

Time:12-02

The code below in my functions.php file allows me to add a block on the Checkout page. This block, if the Cart contains a product with ID "100" with variation "111", suggests adding a product with ID 100 with variation 112. How can I remove the ID="u-1" block if the user clicked on this button and added a product with ID 100 with variation 112 to his Cart?

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>';
}

I know how to hide a block after clicking a button using javascript, but there is a problem: after a product with ID "100" with variation 112 is added to the cart, the page reloads and the block becomes visible again. So I would like to implement this using PHP, but I still cannot figure out how.

CodePudding user response:

Just set the $bool = false if the variation ID is already in your cart

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>';
}
  • Related