functions – Selected product should not be purchased with other products

Question

I am using the following code to complete the selected product (product id:- 209256) automatically, and the code works fine. But I want that the product can’t be purchased with other orders. If someone tries to purchase the product with other products, a notice should display “The item can only be bought in a single order. “

add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' ); 
function custom_woocommerce_auto_complete_order( $order_id ) {  
if ( ! $order_id ) {
    return;
}

$order = wc_get_order( $order_id );

$product_ids   = array('209256'); // Here set your targeted product(s) Id(s)
$product_found = false;

// Loop through order items
foreach ( $order->get_items() as $item ) {
    if( array_intersect( $product_ids, array($item->get_product_id(), $item->get_variation_id()) ) ) {
        $product_found = true;
        break;
    }
}

if( $order->has_status( 'processing' ) && $product_found ) {
    $order->update_status( 'completed' );
} }

I have already enabled “Enable this to only allow one of this item to be bought in a single order”, but this only option disabled the multiple quantities option.

enter image description here

0
James14865 7 months 2022-01-15T12:12:50-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse