Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.5 kB
0
Indexable
Never
function check_and_remove_pre_order_items() {
    // Get cart items
    $cart = WC()->cart->get_cart();
    $pre_order_items = [];
    $non_pre_order_items = [];

    // Separate pre-order and non pre-order items
    foreach ($cart as $cart_item_key => $cart_item) {
        $is_pre_order = get_post_meta($cart_item['product_id'], '_is_pre_order', true);
        if ($is_pre_order === 'yes') {
            $pre_order_items[$cart_item_key] = $cart_item;
        } else {
            $non_pre_order_items[$cart_item_key] = $cart_item;
        }
    }

    // Check if both pre-order and non pre-order items are in the cart
    if (!empty($pre_order_items) && !empty($non_pre_order_items)) {
        $removed_items_names = [];

        // Remove pre-order items from the cart
        foreach ($pre_order_items as $cart_item_key => $cart_item) {
            WC()->cart->remove_cart_item($cart_item_key);
            $removed_items_names[] = $cart_item['data']->get_name();
        }

        // Display notice
        $removed_items_names_string = implode(', ', $removed_items_names);
        wc_print_notice(
            sprintf(
                'You can only order preorder / cart items in separate orders. We have removed the following items from your cart: %s. Please order such pre-order items in a separate order.',
                $removed_items_names_string
            ),
            'error'
        );
    }
}

add_action('woocommerce_check_cart_items', 'check_and_remove_pre_order_items');
Leave a Comment