admin管理员组文章数量:1426594
I want to add a custom meta data for all the users with a default false value. I have researched about adding a meta data i.e, add_user_meta( int $user_id, string $meta_key, mixed $meta_value, bool $unique = false )
which allows only adding a meta data to a particular user. But I want to add it for all the users.
How can I achieve this?
Thanks.
I want to add a custom meta data for all the users with a default false value. I have researched about adding a meta data i.e, add_user_meta( int $user_id, string $meta_key, mixed $meta_value, bool $unique = false )
which allows only adding a meta data to a particular user. But I want to add it for all the users.
How can I achieve this?
Thanks.
1 Answer
Reset to default 2Adding custom field to all existing users.
You will have to get the list of users and then, in a loop, set a custom field for each of them.
$users = get_users( [
'fields' => 'id',
'meta_key' => 'YOUR_META_KEY',
'meta_compare' => 'NOT EXISTS'
] );
if ( is_array($users) && count($users) )
{
$meta_value = false;
foreach( $users as $user_id ) {
add_user_meta( $user_id, 'YOUR_META_KEY', $meta_value, true);
}
}
The version with a single query requires the use of an SQL query. The function will return FALSE in case of error.
global $wpdb;
$sql_query = "INSERT INTO {$wpdb->usermeta} (user_id, meta_key, meta_value) "
. "SELECT ID, 'YOUR_META_KEY', '' FROM {$wpdb->users} u "
. " LEFT JOIN {$wpdb->usermeta} um ON um.user_id = u.ID AND um.meta_key='YOUR_META_KEY' "
. " WHERE um.umeta_id IS NULL";
$result = $wpdb->query( $sql_query );
Above code should be run once.
Example:
functions.php
add_action( 'init', 'se338136_add_meta_to_existing_users' );
function se338136_add_meta_to_existing_users() {
$option_meta_name = '_my_meta_added';
$executed = get_option( $option_meta_name, false );
if ( $executed == 1 )
return;
// here one of the above codes
// if ($result !== false )
update_option( $option_meta_name, 1 );
}
Adding a custom field when adding a new user.
add_filter( 'insert_user_meta', 'new_user_meta', 20, 3);
/**
* @param array $meta Default meta values and keys for the user.
* @param WP_User $user User object.
* @param bool $update Whether the user is being updated rather than created.
*/
function new_user_meta( $meta, $user, $update )
{
if ( $update )
return $meta;
$meta['YOUR_META_KEY'] = false;
return $meta;
}
References:
- get_users
- $wpdb->query
- insert_user_meta
本文标签: Add custom user meta data
版权声明:本文标题:Add custom user meta data 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745483130a2660264.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论