你分享的代码有点神秘,但我会尽力给你答案的。
从概念上讲,您只需获取元数据,更新它,然后重写它。
所以,一旦你的元值被写入,当你想要更新时,你会这样做:
// 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);
}
然后您可以使用该函数更新用户元数据,如下所示:
// Add the "Value 2" to the array of meta values for user 1
my_meta_update(1, 'my_meta_key', 'Value 2');
奖金
应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);
}
用法:
// Remove "Value 2" from the array of meta values for user 1
my_meta_remove(1, 'my_meta_key', 'Value 2');