Hook woocommerce_checkout_order_processed order items issue

Tags: , , , ,



I am working on a WooCommerce project. I need to add some entry based on ordered item in my custom table. If user ordered 3 items then those 3 entry will be place along with some data in my custom table.

For that I used woocommerce_checkout_order_processed hook. But I faced some issue, that if user adds 4 items in cart and on checkout page if user removed all items except one and finally ordered just 1 item then also in this hook I am getting all 4 items. I am not getting final ordered item in this hook.

So I changed the hook to woocommerce_thankyou . But in some case due to some reason user did not come on thank you page or on some credit card payment this hook did not work.

So can anyone tell me the best hook which can run after order place no matter if payment done or not and also I should get only ordered items. My WooCommerce version is 3+

Code :

function wc_function($order_id) {
    global $wpdb;
    $order = new WC_Order($order_id);
    $items = $order->get_items();
    foreach ($items as $item_line_id => $item) {
        // Insert data in my custom table
    }
}
//add_action('woocommerce_checkout_order_processed','wc_function', 10, 3);
//add_action('woocommerce_thankyou', 'wc_function', 10, 1);

Thank you !

Answer

do_action on woocommerce_checkout_order_processed passes exactly three args, third of which is the $order itself. So try using that instead:

function wc_function($order_id, $posted_data, $order) {
    $items = $order->get_items();
    foreach ($items as $item_line_id => $item) {
        // Insert data in my custom table
    }
}


Source: stackoverflow