允许客户在WooCommerce中更改订单状态

时间:2020-07-24 03:59:29

标签: php wordpress woocommerce

在WooCommerce中,当订单处于处理状态时,我想在“我的帐户”页面上显示一个操作按钮,允许客户通过更改订单状态以完成来确认订单已到达。

我看过Allowing customer to change status of the order via email个相关的问题代码(没有答案),这对实现我的目标并没有真正的帮助。

客户是否可以通过将订单状态更改为“已完成”来确认订单是否已到达?

1 个答案:

答案 0 :(得分:2)

您可以使用woocommerce_my_account_my_orders_actions向“我的帐户”订单部分添加自定义操作按钮,以获取状态为“处理中”的订单(也可以查看订单)。

然后使用template_redirect挂钩,客户可以更改其处理订单之一的状态,并显示成功通知。

代码:

// The button Url and the label
function customer_order_confirm_args( $order_id ) {
    return array(
        'url'  => wp_nonce_url( add_query_arg( 'complete_order', $order_id ) , 'wc_complete_order' ),
        'name' => __( 'Approve order', 'woocommerce' )
    );
}

// Add a custom action button to processing orders (My account > Orders)
add_filter( 'woocommerce_my_account_my_orders_actions', 'complete_action_button_my_accout_orders', 50, 2 );
function complete_action_button_my_accout_orders( $actions, $order ) {
    if ( $order->has_status( 'processing' ) ) {
        $actions['order_confirmed'] = customer_order_confirm_args( $order->get_id() );
    }
    return $actions;
}

// Add a custom button to processing orders (My account > View order)
add_action( 'woocommerce_order_details_after_order_table', 'complete_action_button_my_accout_order_view' );
function complete_action_button_my_accout_order_view( $order ){
    // Avoiding displaying buttons on email notification
    if( is_wc_endpoint_url( 'view-order' ) ) {
        $data = customer_order_confirm_args( $order->get_id() );

        echo '<div style="margin:16px 0 24px;">
            <a class="button" href="'.$data['url'].'">'.$data['name'].'</a>
        </div>';
    }
}

// Change order status and display a message
add_action( 'template_redirect', 'action_complete_order_status' );
function action_complete_order_status( $query ) {
    if ( ( is_wc_endpoint_url( 'orders' )
        || is_wc_endpoint_url( 'view-order' ) )
        && isset( $_GET['complete_order'] )
        && $_GET['complete_order'] > 1
        && isset($_GET['_wpnonce'])
        && wp_verify_nonce($_GET['_wpnonce'], 'wc_complete_order') )
    {
        $order = wc_get_order( absint($_GET['complete_order']) );

        if ( is_a($order, 'WC_Order') ) {
            // Change order status to "completed"
            $order->update_status( 'completed', __('Approved by the customer', 'woocommerce') ) ;

            // Add a notice (optional)
            wc_add_notice( sprintf( __( 'Order #%s has been approved', 'woocommerce' ), $order->get_id() ) );

            // Remove query args
            wp_redirect( esc_url( remove_query_arg( array( 'complete_order', '_wpnonce' ) ) ) );
            exit();
        }
    }
}

代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。

相关的(旧答案)Allow customer to change the order status in WooCommerce My account