0

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 (Users > Add New) and the woocommerce order 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 woocommerce order user registration form get the user-meta "member_id" field. They are subscribers. I don't understand why...

0
Try this:

function assignuserid($user_id) {

    $user_meta = get_userdata($user_id); 

    $user_roles = $user_meta->roles;

    if (in_array("subscriber", $user_roles)){
        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');
| improve this answer | |

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.