questions

How to add order in processing if user is returning using?

Rate this post

I have been using the “Cash on Delivery” payment method in Woocommerce and added custom Order Status “COD” in Woocommerce. I have been using the following code to move orders to “COD” if the user selected the “COD” payment option.

add_filter( 'woocommerce_cod_process_payment_order_status', 'change_cod_payment_order_status', 10, 2 );
function change_cod_payment_order_status($order_status, $order) {
   return 'cod';
}

 

✔️Solution:

If I understand your question you want to set the order status to processing if the user is a returned customer.

Let us assume returned customer means the user has already bought something from you.

function is_order_has_shipping_product( $order_id ) {
    if( ! $order_id ) return;
    $order = wc_get_order( $order_id );
    $items = $order->get_items(); // Get All The Order Items
    $found = false;

    foreach ( $items as $item ) {

        $product_id = $item->get_product_id(); // Get The Item Product ID
        $product    = wc_get_product($product_id);
        $is_virtual = $product->is_virtual(); 


        if(!$is_virtual) {
            $found = true;
            break; // If not virtual then stop the loop
        }
    }


     return $found ;

}

The above function will check if an order has any product other than the virtual product.

    function is_returning_customer($user_id = null) {
    
    if( !$user_id ){
     $user_id = get_current_user_id();
    }

    // Get all customer orders
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => $user_id,
        'post_type'   => 'shop_order', // WC orders post type
        'post_status' => 'wc-completed', // Only orders with status "completed"
        'fields'      => 'ids'
    ) );

    $is_returning_customer = false;
    if( count( $customer_orders ) > 0){

        foreach($customer_orders as $order_id){

           $has_shipping_product =  is_order_has_shipping_product( $order_id );
           if($has_shipping_product){
                $is_returning_customer = true;
                break;
           }

        }
    }
   return $is_returning_customer;
}

So we can use the above function to determine the returning status. You can change the logic if you have any. So now coming to the status change.

add_filter( 'woocommerce_cod_process_payment_order_status', 'change_cod_payment_order_status', 10, 2 );
function change_cod_payment_order_status( $order_status, $order ) {

    $user_id               = $order->get_user_id();
    $is_returning_customer = is_returning_customer($user_id);

    if($is_returning_customer){
        return 'processing';
    }

    return 'cod';
}

Leave a Reply

Your email address will not be published.

Back to top button