I think you are making this a lot harder than it has to be.
- Run your code on
user_register
andupdate_profile
- Check to see if the post exists, and create it if not
- Done. WordPress should take care of the rest.
Something like:
function register_user_pupil($user_id) {
$current_user = new WP_User($user_id);
$post_args = array(
'post_title' => $current_user->data->display_name,
'post_type' => 'pupil',
'post_status' => 'draft', //This registration cpt is not available for public
'post_author' => $current_user->ID
);
$exists = new WP_Query($args);
if (!$exists->have_posts()) {
$postid_pupil = wp_insert_post( $post_args );
}
//postid should return something above 0 and not a WP_Error-object
if (is_array($postid_pupil) || intval($postid_pupil) === 0) {
throw new Exception('Kan inte skapa en elev-registrering');
}
//Rest of updating is done by function postsubmit() (saving the pupil CPT)
}
add_action( 'profile_update', 'register_user_pupil');
add_action( 'user_register', 'register_user_pupil');
I don’t have your CPT and supporting code so I can’t really test that but I am pretty sure it is close.
WordPress will enforce unique email addresses so I don’t see the point of worrying about that.