将值添加到数组中的用户元字段

des*_*eit 4 php arrays wordpress

我想为用户元字段提供以下数据库条目:

meta_key => array ('value 1', 'value 2', 'value 3')
Run Code Online (Sandbox Code Playgroud)

我尝试通过第一次推送创建用户元字段:

update_user_meta(
$user->id,
    meta_key,
    array ($value1)
);
Run Code Online (Sandbox Code Playgroud)

现在我想向数组添加新值。但我不想失去第一个。这怎么可能?add_user_meta 不起作用,因为它一直在添加新的数据库条目。

ran*_*ame 5

你分享的代码有点神秘,但我会尽力给你一个答案。

从概念上讲,您只想先获取元数据,更新它,然后重写它。

所以,一旦你的元值被写入,当你想要更新时,你会做这样的事情:

// Lets create a reusable function for simplicity
/*
 * @param int $user id
 * @param string $meta_key
 * @param string $new_value - the new value to be added to the array
 */
function my_meta_update($user_id, $meta_key, $new_value) {
    // Get the existing meta for 'meta_key'
    $meta = get_user_meta($user_id, $meta_key, false);
    // Do some defensive coding - if it's not an array, set it up
    if ( ! array($meta) ) {
        $meta = array();
    }
    // Push a new value onto the array
    $meta[] = $new_value;
    // Write the user meta record with the new value in it
    update_user_meta($user_id, $meta_key, $meta);
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用该函数更新用户元数据,如下所示:

// Add the "Value 2" to the array of meta values for user 1
my_meta_update(1, 'my_meta_key', 'Value 2');
Run Code Online (Sandbox Code Playgroud)

奖金
在OP的要求,这里除去值的方法:

/**
 * @param int $user_id
 * @param string $meta_key
 * @param string $remove_value - the value to remove from the array
 */
function my_meta_remove($user_id, $meta_key, $remove_value) {
    $meta = get_user_meta($user_id, $meta_key, false);
    // Find the index of the value to remove, if it exists
    $index = array_search($remove_value, $meta);
    // If an index was found, then remove the value
    if ($index !== FALSE) {
        unset($meta[$index]);
    }
    // Write the user meta record with the removed value
    update_user_meta($user_id, $meta_key, $meta);
}
Run Code Online (Sandbox Code Playgroud)

用法:

// Remove "Value 2" from the array of meta values for user 1
my_meta_remove(1, 'my_meta_key', 'Value 2');
Run Code Online (Sandbox Code Playgroud)