Create membership number for existing/new users

275 Views Asked by At

I have a membership site with 4000+ users currently on it.

I am needing to give both new/existing users an automatic ID number.

its very similar to this: Create Unique ID for user

However, this only works for new users, I need it to work for the current users too. So for instance, user id 3421 would get membership number 3421.

This is what I have so far: (pretty much all from above link)

function fb_add_custom_user_profile_fields( $user ) { ?>
        <h3><?php _e('Extra Profile Information', 'Avada'); ?></h3>
            <table class="form-table">
                <tr>
                    <th>
                        <label for="memnumber"><?php _e('Membership Number', 'Avada'); ?>
                        </label>
                    </th>
                    <td>
                    <input type="text" name="memnumber" id="memnumber" value="<?php echo esc_attr( get_the_author_meta( 'memnumber', $user->ID ) ); ?>" class="regular-text" /><br />
                    </td>
                </tr>
            </table>
        <?php }

    function fb_save_custom_user_profile_fields( $user_id ) {
        if ( !current_user_can( 'edit_user', $user_id ) )
            return FALSE;
        update_usermeta( $user_id, 'memnumber', $_POST['memnumber'] );
    }
    add_action( 'show_user_profile', 'fb_add_custom_user_profile_fields' );
    add_action( 'edit_user_profile', 'fb_add_custom_user_profile_fields' );
    add_action( 'personal_options_update', 'fb_save_custom_user_profile_fields' );
    add_action( 'edit_user_profile_update', 'fb_save_custom_user_profile_fields' );




    add_action( 'user_register', 'assignuserid');

    function assignuserid($user_id) {
    global $wpdb;
    $latestid=$wpdb->get_var("SELECT meta_value from $wpdb->usermeta where meta_key='memnumber' order by meta_value DESC limit 1;");
    update_user_meta( $user_id, 'memnumber', $latestid +1 );
}

The solution would need to be safe for the current users.

Any advice would be appreciated.

1

There are 1 best solutions below

4
On

from the docs, the update_user_meta function returns the 'Meta ID if the key didn't exist, true on successful update, false on failure or if the value passed to the function is the same as the one that is already in the database.'

So something like

<?php

$new_user_num = $_POST['memnumber'];

// Assume existing user memnumber update to their id
$res = update_usermeta( $user_id, 'memnumber', $user_id);


if (! $res) { // New user, memnumber set already or failures
    $create_res = update_usermeta( $user_id, 'memnumber', $new_user_num);
    if (! $create_res)
        return 1;
}
return 0;

?>