Skip to content

Instantly share code, notes, and snippets.

@Acephalia
Last active January 22, 2025 21:41
Show Gist options
  • Select an option

  • Save Acephalia/873f1a6c13e842a8c62aa73a1b976231 to your computer and use it in GitHub Desktop.

Select an option

Save Acephalia/873f1a6c13e842a8c62aa73a1b976231 to your computer and use it in GitHub Desktop.
Auto Complete Woocommerce Virtual Orders
add_action('woocommerce_thankyou', 'virtual_orders_that_cleanup_after_themselves', 10, 1 );
function virtual_orders_that_cleanup_after_themselves( $order_id ) {
if( ! $order_id ) return;
// Get order
$order = wc_get_order( $order_id );
// get order items = each product in the order
$items = $order->get_items();
// Set variable
$only_virtual = true;
foreach ( $items as $item ) {
// Get product id
$product = wc_get_product( $item['product_id'] );
// Is virtual
$is_virtual = $product->is_virtual();
// Is_downloadable
$is_downloadable = $product->is_downloadable();
if ( ! $is_virtual && ! $is_downloadable ) {
$only_virtual = false;
}
}
// true
if ( $only_virtual ) {
$order->update_status( 'completed' );
}
}
@dax702
Copy link
Copy Markdown

dax702 commented May 7, 2024

Hello, did you write this snippet? Are you available for modifying it? If so, please email me dax702 at gmail

@TheDanHealy
Copy link
Copy Markdown

Thanks for this. I made a slight update which only executes this if all items in the order are virtual.

// Auto-complete virtual orders if payment is completed by u/acephaliax
function auto_complete_virtual_orders($order_id) {
    if (!$order_id) {
        return;
    }

    // Get the order object
    $order = wc_get_order($order_id);

    // If any products are not virtual, exit this function
    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        if ($product && !$product->is_virtual()) {
            return;
        }
    }

    // If you've made it this far, there are only virtual products in your order.
    // If the payment is completed too, auto-complete the order
    if ( $order->is_paid() ) {
        $order->update_status('completed');
    }
}
add_action('woocommerce_order_status_changed', 'auto_complete_virtual_orders', 10, 3);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment