Hi there, I would really appreciate some help - can you point me in the right direction?
On my website, the Admin creates a User. On saving that new user, I have a function that creates a new CPT post called Teacher with the same details as the newly created user - i.e. First Name, Last name, Email.
The proble I now face however, is that the Admin wants to be able to Edit the user through CRED and not only update the USER fields but also the CPT Post TEACHER with the new details (i.e. different name and email).
Please see attachments (screenshots) and code for context:
This code Creates the New Teacher post intially. Is there something I can copy from here for the Save data on the CREDE Edit form. A user will only have ONE Teacher post assigned to them:
// Add relationship between author and child (School Lead and new teacher).
add_action('cred_save_data', 'my_save_data_action_teacher',10,2);
function my_save_data_action_teacher($post_id, $form_data)
{
$form_id = array( 15530 );
if ( in_array( $form_data['id'], $form_id ) ) {
{
$current_user_id = get_current_user_id();
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$user_email = $_POST['user_email'];
$the_role = get_user_meta( $post_id, 'user_role', true );
$new_title = $first_name . " " . $last_name;
$new_title = sanitize_text_field( $new_title );
$my_post = array(
'post_title' => $new_title,
'post_status' => 'publish',
'post_author' => $post_id,
'post_type' => 'teachers'
);
// Insert the post into the database
// Insert the post into the database and save new Client post ID
$new_post_id = wp_insert_post( $my_post );
// Update any custom fields on Client Post
update_post_meta( $new_post_id, 'wpcf-first-name', $first_name );
update_post_meta( $new_post_id, 'wpcf-last-name', $last_name );
update_post_meta( $new_post_id, 'wpcf-teacher-email', $user_email );
update_post_meta( $new_post_id, 'wpcf-user-id', $post_id );
update_post_meta( $new_post_id, 'wpcf-teacher-role', $the_role);
}
}
}
I believe the same setup will work for the edit form, however instead of using the wp_insert_post() function to create the new teacher post. You will need to use the wp_update_post instead in order to update the existing post. https://developer.wordpress.org/reference/functions/wp_update_post/
Thanks so much for your help. So on the CRED function for Save data on my User Edit form, would I need to get the post type I'm trying to update - how would I make sure it only updates the one related to the specific User being edited in the frontend form?
I think I can put together the rest just need a little help with that first bit