![](/img/trans.png)
[英]How to update meta value using update_user_meta in WordPress?
[英]Wordpress how to calculate a value for a user and update related custom meta field
我使用Elementor Pro
在 Wordpress 上創建了一個前端表單,並且在提交時成功更新了登錄用戶的用戶元數據。
我現在想使用表單中提交的值計算一個單獨的自定義元字段。
換句話說:當用戶提交自定義字段straight_speed
的值時,我想使用剛剛輸入的值自動計算straight_speed_percent
百分比,並將其保存給用戶。
現在, straight_speed_percent
的計算可以只是straight_speed
乘以100。
( straight_speed_percent
的自定義字段已經創建)。
最初需要為straight_speed_percent
添加一個值,但如果重新提交表單並更改straight_speed
鏈速度,我希望更新該值。
我已經嘗試了以下代碼,但它似乎不起作用。 任何幫助將不勝感激!
$current_user = wp_get_current_user();
$current_user->ID;
$straight_speed = get_user_meta ('straight_speed', $current_user);
$straight_acceleration_percent_value = $straight_speed * '100';
update_user_meta( $current_user, 'straight_acceleration_percent', '$straight_acceleration_percent_value' );
您的代碼中存在一些語法和邏輯錯誤!
get_user_meta
您需要使用$current_user->ID
和meta key
。 閱讀文檔了解更多詳情!$straight_speed
變量保存到數據庫時,它將被保存為文本字符串,因此當您從數據庫中取回它時,將其轉換為整數,然后進行乘法運算!$straight_acceleration_percent_value
變量周圍還有額外的引號!使用以下代碼段:
$current_user = wp_get_current_user();
$straight_speed = get_user_meta($current_user->ID, 'straight_speed', true);
if ($straight_speed) {
$straight_acceleration_percent_value = (int)$straight_speed * 100;
update_user_meta($current_user->ID, 'straight_speed_percent', $straight_acceleration_percent_value);
}
這個答案已經過測試並且工作正常! 讓我知道它是否也適合你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.