当用户注册时,我具有以下工作代码来创建新的CPT条目,但是现在我仅在用户具有订阅者角色时才需要执行此操作。该注册由WooCommerce处理。我通过主题我的登录名有另一种形式的另一个用户角色。
$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))可以正常工作
我终于通过使用“ woocommerce_checkout_subscription_created”而不是“ user_register”解决了它
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句