函数文档

update_user_meta()

💡 云策文档标注

概述

update_user_meta() 函数用于基于用户ID更新用户元数据字段。如果元字段不存在,则会自动添加。该函数是 update_metadata() 的封装,专门处理用户元数据。

关键要点

  • 参数:$user_id(整数,必需)、$meta_key(字符串,必需)、$meta_value(混合类型,必需,非标量需可序列化)、$prev_value(混合类型,可选,用于指定更新前检查的旧值)。
  • 返回值:元ID(如果键不存在)、true(更新成功)、false(失败或新值与数据库现有值相同)。
  • 使用 $prev_value 参数可以区分具有相同键和用户ID的多个元字段,否则会更新所有匹配条目。
  • 历史原因要求输入时元键和元值需进行“斜杠转义”。
  • 与已弃用的 update_usermeta 相比,行为变化包括:新值为空时不删除元数据,且操作不同。

代码示例

// 示例:更新用户元数据,检查错误
$user_id = 1;
$new_value = 'some new value';
$updated = update_user_meta( $user_id, 'some_meta_key', $new_value );
if ( $new_value != get_user_meta( $user_id, 'some_meta_key', true ) ) {
    wp_die( __( 'An error occurred', 'textdomain' ) );
}

注意事项

  • 当存在多个相同键的元字段时,需谨慎使用 $prev_value 参数以避免意外更新所有条目。
  • 非标量元值(如数组或对象)必须可序列化。
  • 函数不会因新值为空而删除元字段,这与旧版本行为不同。

📄 原文内容

Updates user meta field based on user ID.

Description

Use the $prev_value parameter to differentiate between meta fields with the same key and user ID.

If the meta field for the user does not exist, it will be added.

For historical reasons both the meta key and the meta value are expected to be “slashed” (slashes escaped) on input.

Parameters

$user_idintrequired
User ID.
$meta_keystringrequired
Metadata key.
$meta_valuemixedrequired
Metadata value. Must be serializable if non-scalar.
$prev_valuemixedoptional
Previous value to check before updating.
If specified, only update existing metadata entries with this value. Otherwise, update all entries. Default empty.

Return

int|bool Meta ID if the key didn’t exist, true on successful update, false on failure or if the value passed to the function is the same as the one that is already in the database.

More Information

Changes in behavior from the now deprecated update_usermeta:

Update_user_meta does not delete the meta if the new value is empty.

The actions are different.

Source

function update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' ) {
	return update_metadata( 'user', $user_id, $meta_key, $meta_value, $prev_value );
}

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    update_user_meta() will update ALL user meta of the same key UNLESS you specify a specific record out of the set that you want to replace.

    Here’s a way to do that, specifically for the instance where you have user meta that may look like this:

    +---------+----------------------+-----------------
    | 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: <a href="http://php.net/manual/en/function.array-search.php#116635" rel="nofollow ugc">http://php.net/manual/en/function.array-search.php#116635</a>
    $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 ] );
    }

  2. Skip to note 4 content

    how to check for errors

    $user_id = 1;
    $new_value = 'some new value';
    
    // Will return false if the previous value is the same as $new_value.
    $updated = update_user_meta( $user_id, 'some_meta_key', $new_value );
    
    // So check and make sure the stored value matches $new_value.
    if ( $new_value != get_user_meta( $user_id,  'some_meta_key', true ) ) {
    	wp_die( __( 'An error occurred', 'textdomain' ) );
    }