[英]Get user custom meta data value and update it in WooCommerce orders
在 woocommerce 中,我正在嘗試向現有的 php 代碼添加其他代碼,該代碼將值存儲到數據庫中的高級客戶字段。
如您所見,我通過添加不同的值來計算值“Kontostandeintrag”,並將該值存儲在字段“Kontostandeintrag”的 post_meta 中。 我對每個訂單行都這樣做。
這工作正常。
作為下一步,我想讀取 user_meta 中現有的客戶字段“_kontostandaktuell”(對於訂單行的客戶),將實際值“Kontostandeintrag”添加到該字段並再次使用總和值更新字段“_kontostandaktuell”這個領域的。 因此,在遍歷所有訂單行之后,我應該在 user_meta 字段“_kontostandaktuell”中為每個客戶提供所有“Kontostandeintrag”值的總和值。
獲取用戶自定義元數據值並在 WooCommerce 中更新
我想擴展的現有代碼是:
add_filter('woe_get_order_value_Kontostandeintrag', function( $value, $order, $fieldname ) {
$id = $order->get_id();
$value =get_post_meta($id,"GS-Bargeldeinzahlung",true) + $order->get_total() + get_post_meta($id,"GS-Mitgliedsbeitrag",true) + get_post_meta($id,"GS-Nachlass",true) + get_post_meta($id,"GS-Guthabenkonto",true);
global $wpdb;
$data = array("meta_value" =>$value);
$where = array("post_id"=>$id,"meta_key" =>"Kontostandeintrag");
$wpdb->update( "wp_postmeta", $data, $where );
return $value;
},10,3);
由於 Woocommerce 3,您的代碼有點過時,您不需要使用任何 SQL 查詢。 所以我重新審視了你的代碼,在可用的WC_Order
Object 上使用了一些WC_Data
方法。
現在另外,在這個 function 中,我們從用戶元鍵“_kontostandaktuell”中獲取元值,然后更新該元值,將計算值添加到它。
編碼:
add_filter('woe_get_order_value_Kontostandeintrag', 'filter_get_order_value_kontostandeintrag', 10, 3 );
function filter_get_order_value_kontostandeintrag( $value, $order, $fieldname ) {
// Calculation from different order meta values
$value = $order->get_total() +
$order->get_meta('GS-Bargeldeinzahlung') +
$order->get_meta('GS-Mitgliedsbeitrag') +
$order->get_meta('GS-Nachlass') +
$order->get_meta('GS-Guthabenkonto');
// Update order meta value for "Kontostandeintrag" key
$order->update_meta_data('Kontostandeintrag', $value );
$order->save(); // Save to database
// Get the User ID from order
$user_id = $order->get_customer_id();
// Get user meta value for "_kontostandaktuell" key
$kontostandaktuell = get_user_meta( $user_id, '_kontostandaktuell', true );
// Update user meta value for "_kontostandaktuell" key
update_user_meta( $user_id, '_kontostandaktuell', $kontostandaktuell + $value );
return $value;
}
它應該工作。
相關 WordPress 用戶函數文檔: get_user_meta()
和update_user_meta()
添加(與您的評論有關) :
要在之前重置_kontostandaktuell
用戶字段,您應該從代碼中刪除:
// Get user meta value for "_kontostandaktuell" key
$kontostandaktuell = get_user_meta( $user_id, '_kontostandaktuell', true );
並從update_user_meta()
function $kontostandaktuell +
中刪除,因此您將擁有:
update_user_meta( $user_id, '_kontostandaktuell', $value );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.