首页 > 解决方案 > WordPress update_user_meta 确实适用于变量

问题描述

我正在尝试通过调用该update_user_meta()函数来更新用户的元数据,但不是更新值,而是在数据库中将其设置为null

此外,该值将设置为null,即使它具有已为 that 设置的相同值meta_key

奇怪的是,update_user_meta()如果我将静态文本“例如 MyValue”传递给函数而不是变量,那么工作就很好。

$phone = $_POST["PHONENUMBER"]; //has value 12345

$current_user = wp_get_current_user();

echo 'Updating phone to value: ' . $phone . ' </br>';
//Output is "Updating phone to value: 12345"

//This will set lc-phone value to NULL even if the old value would have been 12345. 
update_user_meta($current_user->ID, 'lc-phone', $phone);

//this will update the lc-phone value to 12345
update_user_meta($current_user->ID, 'lc-phone', '12345');

我还在update_metadata().meta.php

echo var_dump($meta_value) . '</br>';

但是两种情况下的输出都是: string(5) "12345"

谁能说出这些调用变量与静态文本有什么区别?

标签: phpwordpress

解决方案


您应该在更新数据库之前检查 $_POST 值。

if( isset($_POST['phonenumber']) and is_user_logged_in() ) {

$user_id = get_current_user_id();

//Get phone numer
$phone = sanitize_text_field( $_POST['phonenumber'] );

//Update user meta
update_user_meta( $user_id, 'lc-phone', $phone);
}

验证表单总是非常重要:) 如果 $_POST = null ,这意味着 $_POST 未设置。


推荐阅读