Why can't I add a meta element after order completion?

I want to be able to add metadata to each item in the order after the payment is completed. Below is the code that I still have:

add_action('woocommerce_order_status_completed', array($this, 'action_fuck_it_all')); public function action_fuck_it_all($order_id) { $order = new WC_Order( $order_id ); $items = $order->get_items(); foreach ( $items as $item ) { $product_id = $item['product_id']; $item_id = $item['item_id']; $licence = $this->_getProductLicenseCode($product_id); if( !$licence ){ return false; } woocommerce_add_order_item_meta($item_id, 'attribute_licence_code', $licence->licence_code); $this->_setLicenceCodeStatus($licence->licence_id, 'assigned'); } } protected function _getProductLicenseCode($product_id) { global $wpdb; $query = "SELECT licence_id, product_id, licence_code, licence_status FROM {$wpdb->prefix}wc_product_licences WHERE product_id = $product_id AND licence_code <> '' AND licence_status = 'available' ORDER BY creation_date ASC LIMIT 1"; //print $query.'<br/>'; return $wpdb->get_row($query); } protected function _setLicenceCodeStatus($licence_id, $status) { global $wpdb; $data = array('licence_status' => $status); if( $status == 'assigned' ) { } $wpdb->update($wpdb->prefix . 'wc_product_licences', $data, array('licence_id' => (int)$licence_id)); } 

In accordance with my testing, everything works (obtaining a license, installing a license, changing the status of a license to an assigned one, etc.), except that the license code is not inserted as a meta for each element. Any ideas what is going on?

Thanks!

+4
source share
2 answers

Try to do this on another hook, for example:

 add_action('woocommerce_add_order_item_meta', 'my_order_item_meta'), 10, 2); function my_order_item_meta( $item_id, $values, $cart_item_key ) { $product_id = $values['data']->id; $licence = $this->_getProductLicenseCode($product_id); if( !$licence ){ return false; } wc_add_order_item_meta($item_id, 'attribute_licence_code', $licence->licence_code); $this->_setLicenceCodeStatus($licence->licence_id, 'assigned'); } 
0
source

ok here item_id is not inside $ items, this is the key to $ items

 add_action('woocommerce_order_status_completed', array($this, 'my_machine')); public function my_machine($order_id) { $order = new WC_Order( $order_id ); $items = $order->get_items(); foreach ( $items as $key=>$item ) { $product_id = $item['product_id']; $item_id = $key; $licence = $this->_getProductLicenseCode($product_id); if( !$licence ){ return false; } woocommerce_add_order_item_meta($item_id, 'attribute_licence_code', $licence->licence_code); $this->_setLicenceCodeStatus($licence->licence_id, 'assigned'); } } 
0
source

Source: https://habr.com/ru/post/1502189/


All Articles