首页 > 解决方案 > 如果用户返回使用,如何在处理中添加订单?

问题描述

我一直在 Woocommerce 中使用“货到付款”付款方式,并在 Woocommerce 中添加了自定义订单状态“COD”。如果用户选择“COD”付款选项,我一直在使用以下代码将订单移动到“COD”。

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

标签: wordpress

解决方案


如果我理解您的问题,如果用户是退货客户,您希望将订单状态设置为处理中。

让我们假设返回的客户意味着用户已经从您那里购买了东西。

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 ;

}

上述功能将检查订单是否有虚拟产品以外的任何产品。

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

所以我们可以使用上面的函数来判断返回状态。如果有任何逻辑,您可以更改逻辑。所以现在来到状态变化。

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

推荐阅读