[英]Add value to meta_value in user_meta after order is placed
此 function 使用 meta_first 和 meta_second 值更新 user_meta。 meta_first
是帶有數字的文本框,而meta_second
是選擇框。 現在每個產品都有不同的meta_first
和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);
}
}
當任何用戶為產品下訂單時,假設值為 meta_first 10 的產品一,user_meta 更新為 10。我想要實現的是,如果用戶在 meta_first 20 的值之后下訂單產品二,則 user_meta 應該更新為 10+20。
您應該將 update_post_meta 移出 foreach 塊。
例如,
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.