Home >Backend Development >PHP Tutorial >How Can I Automatically Complete Paid WooCommerce Orders with Conditional Logic?

How Can I Automatically Complete Paid WooCommerce Orders with Conditional Logic?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 10:57:08972browse

How Can I Automatically Complete Paid WooCommerce Orders with Conditional Logic?

Conditional Code for Paid Order Auto Completion in WooCommerce

WooCommerce generally autocompletes orders for virtual products, but this may not occur due to payment method limitations. Here's how to implement conditional code to handle this issue:

Identifying the Filter Hook:

The filter hook to modify the allowed paid order statuses is woocommerce_payment_complete_order_status. This hook is used by all payment methods that require payment during checkout.

Solution for WooCommerce 3 and Above (2019):

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';
}
  • This code changes the allowed paid order statuses to only include "completed".

Improved Version for WooCommerce 3 and Above (2018):

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' );
}
  • This code only updates the status to "completed" for payment methods other than "bacs", "cod", and "cheque".

Original Answer for 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' );
    }
}
  • This code uses get_post_meta() to check for "bacs", "cod", and "cheque" payment methods and skips those orders.

The above is the detailed content of How Can I Automatically Complete Paid WooCommerce Orders with Conditional Logic?. 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