我想要用户元字段具有以下数据库条目:
meta_key => array ('value 1', 'value 2', 'value 3')
我尝试通过第一次推送创建用户元字段:
update_user_meta(
$user->id,
meta_key,
array ($value1)
);
现在,我想向数组添加新值。但是我不想失去第一个。那怎么可能?add_user_meta无法正常工作,因为它一直都在添加新的数据库条目。
您共享的代码有点神秘,但是我会尽力为您提供答案。
从概念上讲,您只想先获取元数据,对其进行更新,然后将其重写。
因此,一旦您的元值被写入,当您想要更新时,您将执行以下操作:
// 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);
}
然后,您可以使用该功能更新用户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');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句