I'm trying to query the database and pass the results to the update_post_meta
function. But not sure if I'm building this correctly or if there's something wrong with my usage of $order_id
?
Once an order is placed, I need to update the post meta with the currently logged in user and the query results for the current order, so thought the woocommerce_thankyou
hook would make sense, but the post meta is not written after the order is completed. < /p>
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); }
Any suggestions on how best to handle this issue?
Your code attempt contains multiple bugs and errors:
woocommerce_thankyou
is an action hook, not a filter hook$order_id
is passed to the callback function,$result
is not applicable$wpdb->prefix
withb03_
, this can make it dynamic$wpdb
is an objectglobal $woocommerce, $post;
is redundantSo you get:
Note: Since you are using a custom SQL query where the data/results don't exist generally/by default in WooCommerce, but just for you, I have replaced it with mine The answer has a fixed value of 10. Adjust as needed!