1

I am tring to build a point system for users. To save points I thought to use user meta. So I need to create a meta user called poins for all cureent users as well as futures users.

add_user_meta function need a user id. So will I have to use a loop?

1 Answer 1

5

yes, you would have to loop through all users so that you could then update that user_meta field:

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query(array('role' => 'Subscriber'));

// Get the results
$users = $wp_user_query->get_results();

// Check for results
if (!empty($users)) {

    // loop trough each author
    foreach ($users as $user)
    {
        // add points meta all the user's data
        add_user_meta( $user->id, 'points', '5', true ); // 5 = number of points existing users will get
    }
}

as far as adding this same user_meta to new users you could hook into the login or registration, depending on how you are adding them to the system. for this you could use get_current_user_id() to get the id of that unique user.

later, you could then just update_user_meta($user_id,'points'); in whatever function they are earning more points at.

you can find more info on the WP_User_Query in the Codex

5
  • After adding this code to functions.php and after a page refresh can I remove the code again?
    – Sugantha
    Commented Apr 7, 2016 at 1:04
  • Yes, you could remove the code once the users received this meta.
    – Ray Flores
    Commented Apr 7, 2016 at 5:07
  • if you like this answer, could you please mark it as 'answered' ?
    – Ray Flores
    Commented Apr 21, 2016 at 19:23
  • What about new users?
    – marek.m
    Commented Jul 24, 2017 at 14:36
  • @marek.m as far as adding this same user_meta to new users you could hook into the login or registration, depending on how you are adding them to the system. for this you could use get_current_user_id() to get the id of that unique user. <- within original answer... you just need to get the id of the user ( through login or registration )... this is obviously dependent on how/where you are capturing the new user info in the first place.
    – Ray Flores
    Commented Jul 25, 2017 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.