Hi,
Upon registering a new user account with a CRED User Form I want to add a new custom post, for which the author is the newly created user and some fields in the new custom post should be filled with the ones from User Form.
Something already discussed here:
https://toolset.com/forums/topic/automatic-custom-post-creation-on-user-registration/
and here:
https://toolset.com/forums/topic/create-a-new-ctp-post-when-a-user-is-created-with-user-registration-a-cred-form/
I managed to do it with the following code:
add_action( 'user_register', 'add_profile' );
function add_profile( $user_id ) {
$my_post = array(
'post_title' => wp_strip_all_tags( $_POST[ 'first_name' ] . " " . $_POST[ 'last_name' ] ),
'post_status' => 'publish',
'post_author' => $user_id,
'post_type' => 'profiles'
);
wp_insert_post( $my_post );
}
But I don't know how to pass data from the CRED User Form to the new post, like first or last name. How to insert data to the custom field of the new post now?
I have replied to several similar requests, in both directions (Post Field to User Fields and vice versa User Fields to Post Fields).
https://toolset.com/forums/topic/update-user-custom-field/
It is usually quite simple, you run get_post_meta() on posts to get the values, update_user_meta() on User Fields to update them, and vice versa you run get_user_meta() to get User Fields and update_post_meta() on Post fields to update them.
DOC:
https://codex.wordpress.org/Function_Reference/update_post_meta
https://codex.wordpress.org/Function_Reference/update_user_meta
https://codex.wordpress.org/Function_Reference/get_user_meta
https://developer.wordpress.org/reference/functions/get_post_meta/
The only exception are Checkboxes Fields, please avoid them if possible in your setups.
The problem is those are arrays of arrays (of arrays) and it is tricky to pass the infos over to other fields of the same type in this case.
When you want to create a Post on each creation of an user, I suggest you get all the data from the user (either from the $_POST if you get it from the CRED Form directly on submit, or from get_user_meta() if after saving) and pack that in the $postarr of wp_insert_post().
Then you can run this for example on cred_save_data() and this will create a new post for the new user.
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
Ok, the following works for me, as I need to set an author for the new post the same as newly created user:
add_action( 'user_register', 'add_member' );
function add_member( $user_id ) {
$new_member = array(
'post_title' => wp_strip_all_tags( $_POST[ 'first_name' ] . " " . $_POST[ 'last_name' ] ),
'post_author' => $user_id,
'post_type' => 'member',
'post_status' => 'publish',
'meta_input' => array(
'wpcf-member-first-name' => $_POST[ 'first_name' ],
'wpcf-member-last-name' => $_POST[ 'last_name' ]
),
);
wp_insert_post( $new_member );
}
Thanks.