I'm currently using a Woocommerce session to save information that the user inputs on the cart page which affects a fee added to the transaction.
I need to be able to access this information right after the order has been completed to make necessary updates to the user's account.
I figured woocommerce_thankyou
would be a good hook to use, but unfortunately the session only seems to be available half of the time.
Are there any better hooks to use where I could confirm that the purchase had been completed and the session information would be available?
You need to save that session data as custom order meta data, to be able to use it afterwards (replace my_key
, in the code below, with the correct session key):
// Add custom order meta data with temporary data from WC_Session
add_action( 'woocommerce_checkout_create_order', 'add_session_data_as_custom_order_meta_data', 10, 2 );
function add_session_data_as_custom_order_meta_data( $order, $data ) {
if ( $session_data = WC()->session->get('my_key') ) {
$order->update_meta_data( '_session_data', $session_data );
}
}
Code goes on function.php file of your active child theme (or theme). Tested and works.
Then to access the data you will use th WC_Data
method get_meta()
on the WC_Order
Object:
$session_data = $order->get_meta('_session_data');
Or also using get_post_meta()
function from a defined order Id:
$session_data = get_post_meta( $order_id, '_session_data', true );