Woocommerce remove specific cart items before viewing the cart

I’m developing a WooCommerce plugin for ordering foods for specific dates from a calendar like weekly list. There is a time limit for orders, you can order for tomorrow on each day until 14:00. It works on the page where you can order the items (the add to cart buttons will not show up if the limit was reached), but if you already have an item in cart which will be unavailable, you CAN order it after 14:00. I read somewhere that there is an action hook for such actions, so i tried to figure it out myself but got stuck.

A little introduction on how it works. When you click on the add to cart button, the item will be created in the cart with a custom meta tag, which contains the infos i need in this format: MenuCode-Year-WeekOfYear-DayOfWeek.

The name of the function is wc_minimum_order_amount, because it also contains a piece of code to show a wc_notice if the order amount is less than a specified amount. This part was removed from the below code because it’s irrelevant to the question, and it works.

And here is the hook and the code that don’t remove the items from the cart:

add_action('woocommerce_checkout_process', 'wc_minimum_order_amount' );
add_action('woocommerce_before_cart' , 'wc_minimum_order_amount' );
function wc_minimum_order_amount() {
    $cart = WC()->cart->get_cart();
    foreach($cart as $item => $values) {
        $co   = explode('-', $values['_custom_options']);
        $year = $co[1];
        $week = $co[2];
        $day  = $co[3];
        $hour = date('H');

        if($year < date('Y')) {
            WC()->cart->remove_cart_item($item);
        }
        else if($year == date('Y') && $week < date('W')) {
            WC()->cart->remove_cart_item($item);
        }
        else if($year == date('Y') && $week == date('W') && $day < date('w')) {
            WC()->cart->remove_cart_item($item);
        }
        else if($year == date('Y') && $week == date('W') && $day == date('w') && $hour >= 14) {
            WC()->cart->remove_cart_item($item);
        }
    }
}

Read more here: Woocommerce remove specific cart items before viewing the cart

Leave a Reply

Your email address will not be published. Required fields are marked *