Add a member number to new user

I need to add a number to user as meta info (it’s a 5 digit number) at the time they register. I assume I would use the user_register action to call a script. I also assume I would use update_user_meta to add the number. But I am not sure how to increment it up one for the next user. Would I have to have a lookup table to see what the last one was? Is there away to look at the last members usermeta(member_number) and then add one? What would be the best way to handle this. There currently exists a roster with assigned numbers, which when I import the users they will receive their number. But after that the next member needs to start at the last number in this roster.

Here is what I tried

    // Add member number at time of registration
global $current_user;
      get_currentuserinfo();

function add_member_no() {
    // just to stick something in the first time.
    $start_no = 507602;
    add_option('member_no', $start_no);

    $last_member_no = get_option(member_no);
    $last_member_no += $last_member_no;
    update_option('member_no', $last_member_no);

    add_user_meta($current_user->id, 'membership_no', $last_member_no);
}
add_action( 'user_register', 'add_member_no');

1 Answer
1

To get the ID of the user that was created last, you could run the following query:

SELECT id FROM wp_users ORDER BY user_registered DESC LIMIT 1

To do this within the context of your code, do this:

global $wpdb;
$last_user_id = $wpdb->get_results("SELECT id FROM $wpdb->users ORDER BY user_registered DESC LIMIT 1");

That will give you access to an instance of the WordPress query object and it will properly the query the database regardless of the table prefix.

You can print_r the result to check the result.

Leave a Comment