У меня есть следующий рабочий код для создания новой записи CPT при регистрации пользователей, но теперь мне нужно, чтобы это происходило , только если пользователь имеет роль подписчика . Эта регистрация обрабатывается WooCommerce. У меня есть другая форма через Theme My Login для другой роли пользователя.
$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);
}
}
Я пробовал с
foreach( $user->roles as $role ) {
if ( $role === 'subscriber' ) {
// code here
}
}
и
if(in_array( 'subscriber', (array) $current_user->roles ) ) {
// code here
}
безуспешно.
Как я могу определить роль пользователя, и только если это подписчик, имеет wp_insert_post?
ОБНОВЛЕНИЕ: фактическая функция, все еще не работает:
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 (! Empty ($ user_roles) && in_array ('subscriber', $ user_roles)) все работает нормально