描述
使用$prev_value参数区分具有相同key和用户ID的meta字段。
如果用户的meta字段不存在,将添加它。
参数
- $user_id
-
(int)(必填) 用户ID。
- $meta_key
-
(string)(必填) meta数据是关键。
- $meta_value
-
(mixed)(必填) meta数据值。如果不是标量,则必须是可序列化的。
- $prev_value
-
(mixed)(可选) 更新前要检查的上一个值。如果指定,则仅使用此值更新现有meta数据项。否则,更新所有条目。
默认值: ''
返回
(int|bool) 如果键不存在则为meta ID,更新成功时为true,失败或者传递给函数的值与数据库中已有的值相同时为false。
更多信息
已弃用的update_usermeta的行为变化:
如果新值为空,则update_user_meta不会删除meta。
动作是不同的。
源码
更新日志
版本 | 描述 |
---|---|
3.0.0 | 开始引入 |
使用示例
update_user_meta()
将更新同一key的所有用户meta,除非您从要替换的集合中指定了特定记录。这里有一种方法可以做到这一点,特别是对于您拥有如下用户meta的实例:
+---------+----------------------+----------------- | user_id | meta_key | meta_value | +---------+----------------------+----------------- | 862 | favorite_coffee | {"coffee_id":10,"title":"Vietnamese Iced Coffee","type":"drip"} | 862 | favorite_coffee | {"coffee_id":11,"title":"Mocha","type":"espresso"} | 862 | favorite_coffee | {"coffee_id":12,"title":"Just An Okay Cappuchino","type":"espresso"}
// dummy data to better show the issue, we want to change the title of `coffee_id` 12 $parameters = array( 'coffee_id' => '12', 'title' => 'A Delicious Cappuchino', 'type' => 'espresso', ); // try to find some `favorite_coffee` user meta $previous_favorite_coffee = get_user_meta( $user_id, 'favorite_coffee', false ); /** * First, the condition for when no favorite_coffee user meta data exists **/ if ( empty( $previous_favorite_coffee ) ) { add_user_meta( $user_id, 'favorite_coffee', $parameters ); } /** * Second, the condition for when some favorite_coffee user_meta data already exists **/ // search recursively through records returned from get_user_meta for the record you want to replace, as identified by `coffee_id` - credit: http://php.net/manual/en/function.array-search.php#116635 $coffee_id = array_search( $parameters['coffee_id'], array_column( $previous_favorite_coffee, 'coffee_id' ) ); if ( false === $coffee_id ) { // add if the wp_usermeta meta_key[favorite_coffee] => meta_value[ $parameters[ $coffee_id ] ] pair does not exist add_user_meta( $user_id, 'favorite_coffee', $parameters ); } else { // update if the wp_usermeta meta_key[favorite_coffee] => meta_value[ $parameters[ $coffee_id ] ] pair already exists update_user_meta( $user_id, 'favorite_coffee', $parameters, $previous_favorite_coffee[ $coffee_id ] ); }
如何检查错误
$user_id = 1; $new_value = 'some new value'; // 如果上一个值和 $new_value 相同,将返回 false $updated = update_user_meta( $user_id, 'some_meta_key', $new_value ); // 所以要检查并确保存储的值与 $new_value 相符 if ( $new_value != get_user_meta( $user_id, 'some_meta_key', true ) ) { wp_die( __( 'An error occurred', 'textdomain' ) ); }