I'm attempting to query my database and pass the result into the update_post_meta function. However not sure if I'm constructing this correcltly or whether there's an issue with my $order_id usage?
I need the post meta to update with the query results for the current logged in user and current order once an order is made, so thought the woocommerce_thankyou hook made sense to use however upon completing an order no post meta is written.
add_filter( 'woocommerce_thankyou', 'my_function', 10, 2);
function my_function( $result, $order_id ) {
// Load the global $post
global $woocommerce, $post;
// Get the post ID
$order_id = $post->ID;
// Then you can get the order object
$order = wc_get_order( $order_id );
$user_ID = get_current_user_id();
//SQL
global $wpdb;
return $wpdb->get_var("SELECT SUM(b03_woocommerce_order_itemmeta.meta_value)
FROM b03_woocommerce_order_itemmeta
JOIN b03_woocommerce_order_items ON b03_woocommerce_order_itemmeta.order_item_id = b03_woocommerce_order_items.order_item_id
JOIN b03_posts ON b03_woocommerce_order_items.order_id = b03_posts.ID
JOIN b03_postmeta ON b03_posts.ID = b03_postmeta.post_id
WHERE b03_posts.post_type = 'shop_order'
AND b03_woocommerce_order_itemmeta.meta_key = 'trees_planted'
AND b03_postmeta.meta_value = $user_ID
AND b03_postmeta.meta_key = '_customer_user'
AND b03_posts.ID = $order_id");
update_post_meta( $order_id, 'trees',$wpdb);
}
Appreciate any advice on how best to handle this?