我在 WP user_meta 表中使用 meta_key
contact
添加了一个用户联系电话。现在我希望元键值是 unique。如何实现?
一个潜在的解决方案如下:
foreach
循环中使用 get_metadata函数来检索元数据字段的值并将它们存储在数组中。
每个步骤如下所示,使用“m520_contact”作为元键(因为建议总是在您的 WP 代码中为所有内容添加前缀)。
第一步
//Get all users with the desired meta key
$users = get_users(array('meta_key' => 'm520_contact'));
第二步
// Store the IDs of all the users obtained in step 1 in an array.
$user_ids = [];
foreach ( $users as $user ) {
array_push($user_ids, $user->data->ID);
}
第三步
/**
*
* Use get_metadata() to retrieve
the values of the metadata field.
*
* get_metadata() returns an array,
so we're using array_shift to
store the returned value as a string.
*
* We'll store the retrieved values
in a variable called $all_meta_values.
*/
$all_meta_values = [];
foreach ($user_ids as $user_id) {
array_push(
$all_meta_values,
array_shift(
get_metadata(
'user',
$user_id, 'm520_contact'
)
)
);
}
第四步
您可以将支票存储在函数中以实现可重用性。例如这样的事情:
/**
* Checks if a value is in the array (unique) before adding it as a meta value.
*/
function m520_is_value_unique(int|string $needle, array $haystack) : bool {
return in_array($needle, $haystack) ? false : true;
}
然后你可以在每次调用
add_user_meta()
或update_user_meta()
之前使用该函数。例如:
if (m520_is_value_unique($new_contact_number, $all_meta_values)) {
add_user_meta(1, 'm520_contact', 1300400500);
}
HTH,姆瓦莱