Last active
June 4, 2024 05:26
-
-
Save willgorham/874c4ac943fc27443cd862a93764d659 to your computer and use it in GitHub Desktop.
WooCommerce: Automatically complete virtual orders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'woocommerce_payment_complete_order_status', 'wmg_auto_complete_virtual_orders', 10, 3 ); | |
/** | |
* Automatically complete orders with only virtual products | |
* | |
* @param string $payment_complete_status Order status used after an order payment is received | |
* @param int $order_id ID of the order being processed | |
* @param WC_Order $order Order object being processed | |
* @return string $payment_complete_status Updated order status | |
*/ | |
function wmg_auto_complete_virtual_orders( $payment_complete_status, $order_id, $order ) { | |
$current_status = $order->get_status(); | |
// We only want to update the status to 'completed' if it's coming from one of the following statuses: | |
$allowed_current_statuses = array( 'on-hold', 'pending', 'failed' ); | |
if ( 'processing' === $payment_complete_status && in_array( $current_status, $allowed_current_statuses ) ) { | |
$order_items = $order->get_items(); | |
// Create an array of products in the order | |
$order_products = array_filter( array_map( function( $item ) { | |
// Get associated product for each line item | |
return $item->get_product(); | |
}, $order_items ), function( $product ) { | |
// Remove non-products | |
return !! $product; | |
} ); | |
if ( count( $order_products ) > 0 ) { | |
// Check if each product is 'virtual' | |
$is_virtual_order = array_reduce( $order_products, function( $virtual_order_so_far, $product ) { | |
return $virtual_order_so_far && $product->is_virtual(); | |
}, true ); | |
if ( $is_virtual_order ) { | |
$payment_complete_status = 'completed'; | |
} | |
} | |
} | |
return $payment_complete_status; | |
} |
The line:
if ( count( $order_products > 0 ) ) {
Needs to be changed to:
if ( count( $order_products ) > 0 ) {
Note the correct placement of the close bracket on the count() function - this fixes the error you are all encountering
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any suggestions for the error thrown below. This was working until some recent updates.