I have the following working code to create a new CPT entry when users register, but now I need this to happen only if the user has a subscriber role. This registration is processed by WooCommerce. I have another form thru Theme My Login for another users role.
$current_user = wp_get_current_user();
add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save( $user_id ) {
$user_info = get_userdata($user_id);
// Here you can insert new post for registered users
$user_profile = array(
'post_title' => 'Profile '.$user_id,
'post_content' => '',
'post_status' => 'publish',
'post_author' => $user_id,
'post_type' => 'profiles'
);
// Insert the post into the database
$post_ID = wp_insert_post($user_profile);
if ($post_ID) {
// update ACF fields
update_field('field_5e0f8b80071a9', $user_info->first_name, $post_ID);
update_field('field_5e107dcfddc77', $user_info->user_email, $post_ID);
}
}
I have tried with
foreach( $user->roles as $role ) {
if ( $role === 'subscriber' ) {
// code here
}
}
and
if(in_array( 'subscriber', (array) $current_user->roles ) ) {
// code here
}
with no success.
How can I detect the user role and only if it is subscriber have the wp_insert_post ?
UPDATE:
the actual function, still not working:
add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save( $user_id ) {
$user_info = get_userdata($user_id);
$user_roles = $user_info->roles; // array with the user's roles
// Here you can insert new post for registered users
$user_profile = array(
'post_title' => 'Profile '.$user_id,
'post_content' => '',
'post_status' => 'publish',
'post_author' => $user_id,
'post_type' => 'profiles'
);
if ( !empty( $user_roles ) && in_array( 'subscriber', $user_roles ) ) {
// Insert the post into the database
$post_ID = wp_insert_post($user_profile);
if ($post_ID) {
// inserisco campi ACF
update_field('field_5e0f8b80071a9', $user_info->first_name, $post_ID);
update_field('field_5e107dcfddc77', $user_info->user_email, $post_ID);
}
}
}
If I comment if ( !empty( $user_roles ) && in_array( ‘subscriber’, $user_roles ) ) it works fine
2
Answers
I finally solved it by using 'woocommerce_checkout_subscription_created' instead of 'user_register'
You are saving the user info inside of the variable
$user_info
. In yourforeach
you are using the variable$user
and in your if clause you are using$current_user
. I think this is the reason it is not working.I would suggest saving the roles of a user inside of a variable and use the
in_array
function. Your code can look like this: