I have created a Forminator Form on my WordPress Site and I want to allow users to create new posts after submitting it. I used Custom Post Type UI Plugin to create a custom slug for the newly created posts. Next, I have written short php code to execute an action after the users submit the form and I have added it to the functions.php file. Below I am providing more information about the names & ids of my fields: Forminator Form ID: 761 Forminator Text Area field name: textarea-1 Custom slug name: view-test-posts Redirect users to the newly created post after form submission
add_action('forminator_custom_form_submit', 'create_post_and_redirect', 10, 2);
function create_post_and_redirect($form_id, $data) {
// Check if the form ID matches
if ($form_id === 761) {
// Get the submitted textarea value
$textarea_value = sanitize_text_field($_POST['textarea-1']);
// Create a new post
$post_data = array(
'post_title' => 'New Test Post',
'post_content' => $textarea_value,
'post_status' => 'publish',
'post_type' => 'view-test-posts', // The custom post type slug
);
// Insert the post into the database
$post_id = wp_insert_post($post_data);
// Check if the post was inserted successfully
if (!is_wp_error($post_id)) {
// Get the URL of the newly created post
$post_url = get_permalink($post_id);
// Redirect to the newly created post URL after successful submission
wp_redirect($post_url);
exit;
} else {
// Handle the error if the post creation fails
$error_message = 'Error creating post: ' . $post_id->get_error_message();
wp_die($error_message);
}
}
}
However, when I submit the form, a new post is not created & I am not redirected to any page. I have tried switching off all plugins except Forminator, Elementor and Custom Post Type UI and the issue remain. Something important to note is that, the form is submitted successfully, and I can see the information under the Submissions section of the Forminator Dashboard.