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?

4

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 Apr 7 '16 at 1:04
  • Yes, you could remove the code once the users received this meta. – Ray Flores Apr 7 '16 at 5:07
  • if you like this answer, could you please mark it as 'answered' ? – Ray Flores Apr 21 '16 at 19:23
  • What about new users? – marek.m Jul 24 '17 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 Jul 25 '17 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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