This function updates user_meta with meta_first and meta_second values.
meta_first
is textbox with number and meta_second
is selectbox.
Now every product will have different values for meta_first
and meta_second
.
// Update user_meta after woocommerce order is placed.
add_action('woocommerce_thankyou' , 'wp_user_meta_update');
wp_user_meta_update($order_id){
# Get an instance of WC_Order object
$order = wc_get_order( $order_id ); //get the order id
$items = $order->get_items(); // get the item
$user_id = $order->get_user_id(); //get the user id
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
foreach ( $items as $item ) {
$product_name = $item->get_name();
$product_id = $item->get_product_id();
$product_variation_id = $item->get_variation_id();
$get_meta_first= get_post_meta( $product_id, 'meta_first', true);
$get_meta_second= get_post_meta( $product_id, 'meta_second', true);
update_user_meta($user_id, 'meta_first' , $meta_first);
update_user_meta($user_id, 'meta_second', $meta_second);
}
}
When any user places an order for a product let's say product one with the value of meta_first 10 the user_meta updates with 10. What I want to achieve is if the user places an order of product two after with the value of meta_first 20 the user_meta should update with 10 20.
CodePudding user response:
You should move update_post_meta out of foreach block.
For example,
$get_meta_first=0;$get_meta_second=0;
foreach ( $items as $item ) {
$product_name = $item->get_name();
$product_id = $item->get_product_id();
$product_variation_id = $item->get_variation_id();
$get_meta_first= $get_meta_first get_post_meta( $product_id, 'meta_first', true);
$get_meta_second= $get_meta_second get_post_meta( $product_id, 'meta_second', true);
}
update_user_meta($user_id, 'meta_first' , $get_meta_first);
update_user_meta($user_id, 'meta_second', $get_meta_second);