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.

Share Improve this question asked May 17, 2019 at 15:18 SubhamSubham 271 gold badge2 silver badges7 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Adding 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