Hi!
How can i create a new user and CPT item in cred form?
I need new user form (to create new account), but this form also create one cpt item with specific taxonomy, fields and this new user created like author.
Hello,
There isn't such a built-in feature within Toolset Forms plugin, one form can handle one post/user at the same time.
If you are familiar with custom codes, you can try these:
1) Create a Toolset user form for creating users.
2) When user submit above form, you can use action hook "cred_save_data" to trigger a custom PHP function:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
Since it is user form, so the first parameter is user's ID, you use user's ID to get user's other information.
For example:
add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($user_id, $form_data)
{
// if a specific form
if ($form_data['id']==123)
{
$user_obj = get_user_by('id', $user_id);
$user_name = $user_obj->user_login;
}
}
3) In this PHP function, create new post with WordPress function
https://developer.wordpress.org/reference/functions/wp_insert_post/
Ok! I use this code (running ok):
add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($user_id, $form_data)
{
// if a specific form
if ($form_data['id'] === 347)
{
$user_obj = get_user_by('id', $user_id);
$user_name = $user_obj->user_login;
sleep(15);
programmatically_create_post($user_id);
}
}
And
function programmatically_create_post($user_id) {
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
// Setup the author, slug, and title for the post
$user_obj = get_user_by('id', $user_id);
$author_id = $user_id;
$user_name = $user_obj->user_login;
$slug = 'example-post';
$title = $user_name;
// If the page doesn't already exist, then create it
if( null == get_page_by_title( $title, 'OBJECT', 'post' ) ) {
// Set the post ID so that we know the post was created successfully
$post_id = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_content' => 'Realizou check-in!!',
'post_status' => 'publish',
'post_type' => 'post',
'tax_input' => array( 'post-type' => array('Checkin', 24))
)
);
// Otherwise, we'll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
} // end if
}
How can i create a relationship in post create via function?
What is the relationship you mentioned above?
If it is post type relationship created with Types plugin, you can try function toolset_connect_posts(), see our document:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_connect_posts
Connects posts within a given post relationship.