0
votes

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 !

1
how are you getting those items in you hook callback? $order->get_items() ?? - Sumit Wadhwa
Hello @swadhwa, Please check my updated question. - David Coder
Yes I am using $order->get_items() to get items. - David Coder
replace function wc_function($order_id) with function wc_function($order_id, $posted_data, $order) it shouldn't make any difference but u could give it a try: $order->get_items() - Sumit Wadhwa
@7uc1f3r, Yes with 3 arguments it is working if we get items direct from arguments. If we use wc_get_order( $order_id )->get_items() then it will return all the items even deleted items from cart page. - David Coder

1 Answers

5
votes

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
    }
}