【问题标题】:Add values to User Meta Field within an array向数组中的用户元字段添加值
【发布时间】:2016-03-04 06:31:54
【问题描述】:

我希望用户元字段具有以下数据库条目:

meta_key => array ('value 1', 'value 2', 'value 3')

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

update_user_meta(
$user->id,
    meta_key,
    array ($value1)
);

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

【问题讨论】:

  • 嗨。您能否修改您的示例代码 - 它实际上没有意义。你可以使用工作代码吗?

标签: php arrays wordpress


【解决方案1】:

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

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

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

// 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');

【讨论】:

  • 是否也可以删除数组的单个值?
  • 当然可以。我将更新答案以包括删除。
【解决方案2】:

关于@cale_b 的回答,我不得不稍微修改一下代码以使其工作。可能是因为答案是 2015 年的更新:

// Do some defensive coding - if it's not an array, set it up
if ( ! is_array($meta) ) {
    $meta = array();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多