Home >Backend Development >PHP Tutorial >How to Automate the Completion of Paid Virtual Product Orders in WooCommerce?

How to Automate the Completion of Paid Virtual Product Orders in WooCommerce?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 18:25:11504browse

How to Automate the Completion of Paid Virtual Product Orders in WooCommerce?

How to Autocomplete Paid Virtual Product Orders in WooCommerce

When a virtual product order is marked as paid, it should typically be automatically set to "completed" status. However, WooCommerce does not always do this. To resolve this issue, you can implement custom code based on the WooCommerce payment method used.

Solution

The following code snippet filters the allowed paid order statuses, effectively completing virtual product orders that are paid via non-excluded payment methods.

add_filter( 'woocommerce_payment_complete_order_status', 'wc_auto_complete_paid_order', 10, 3 );
function wc_auto_complete_paid_order( $status, $order_id, $order ) {
    return 'completed';
}

Explanations

  • Lightweight and Effective: This filter is triggered only when an online payment is required, avoiding unnecessary conditions.
  • Accurate: Prevents multiple customer notifications by setting the order status to "completed" only once.

Alternative Solutions

  • Improved Version (WooCommerce 3 and above):
add_action( 'woocommerce_thankyou', 'wc_auto_complete_paid_order', 20, 1 );
function wc_auto_complete_paid_order( $order_id ) {
    $order = wc_get_order( $order_id );
    if ( in_array( $order->get_payment_method(), array( 'bacs', 'cod', 'cheque', '' ) ) ) {
        return;
    }
    $order->update_status( 'completed' );
}
  • Original Answer (All WooCommerce Versions):
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_paid_order', 10, 1 );
function custom_woocommerce_auto_complete_paid_order( $order_id ) {
    $order = wc_get_order( $order_id );
    if ( ( 'bacs' == get_post_meta($order_id, '_payment_method', true) ) || ( 'cod' == get_post_meta($order_id, '_payment_method', true) ) || ( 'cheque' == get_post_meta($order_id, '_payment_method', true) ) ) {
        return;
    } elseif( $order->get_status() === 'processing' ) {
        $order->update_status( 'completed' );
    }
}

Note: Place the code snippets in the functions.php file of your active child theme or theme.

The above is the detailed content of How to Automate the Completion of Paid Virtual Product Orders in WooCommerce?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn