Saving user meta “member_id” based on user role

Question

In a WP / Woocommerce with subscriptions plugin environment
I manage to save in the user meta table a custom “member_id” at the user creation level:

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

Important: this is working for users of all roles (such as administrator or subscriber) both from the admin backoffice and the user registration form.

Now, when I try to have the member_id generated only for user role = “subscriber” using the code

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

This is working well for users created from the admin backoffice: administrators do not get the member_id, subscribers get the member_id BUT, none of the users created via the user registration form get it. They are subscribers. I don’t understand why…

0
, WPNow 10 months 2020-05-04T06:10:37-05:00 0 Answers 81 views 0

Leave an answer