wordpresscustom-wordpress-pages

Wordpress form submission from front end


I have created a front end page with a form and a function to process the form but at the moment nothing happens after the page "refreshes", I am expecting it to create a post under the custom post type of vendor-review.

function added via snippet:

function vendor_review_handler() {
    // Verify nonce
    if (!isset($_POST['vendor_review_form_nonce']) || !wp_verify_nonce($_POST['vendor_review_form_nonce'], 'vendor_review_form_nonce'))
        die('Security check failed');

    // Get the user ID from the form
    $assigned_to = isset($_POST['assigned_to']) ? intval($_POST['assigned_to']) : 0;

    // Perform form data processing here
    $firstname = sanitize_text_field($_POST['first_name']);
    $lastname = sanitize_text_field($_POST['last_name']);
    $rating = $_POST['rating'];
    $comments = sanitize_textarea_field($_POST['comments']);
        
    $submitform =   wp_insert_post([
            'post_status' => 'publish',
             'post_type'   => 'vendor-reviews',
            'meta_input'  => [
                'first_name' => $firstname,
                'last_name' => $lastname,
                'rating' => $rating,
                'comments' => $comments,
                'assigned_to' => $assigned_to,
                            ]
                ]);
    
    
    
    // Redirect after form submission
    wp_redirect(home_url()); // You can change the URL as needed
    exit;
}

add_action('admin_post_nopriv_vendor_review_handler', 'vendor_review_handler');
add_action('admin_post_vendor_review_handler', 'vendor_review_handler');

and the page:

<!-- wp:code -->
<pre class="wp-block-code"><code>
<form action="" method="post">
    <input type="hidden" name="action" value="vendor_review_handler">
    <label for="first_name">First Name:</label>
      <input type="text" name="first_name" required>
    <label for="last_name">Last Name:</label>
      <input type="text" name="last_name" required>
    <label for="rating">Rating (1-5):</label>
      <input type="number" id="rating" name="rating" min="1" max="5">
    <label for="comments">Comments:</label>
      <textarea id="comments" name="comments" rows="4" cols="50"></textarea>
 <input type="hidden" name="assigned_to" value="<?php echo get_current_user_id(); ?>">
<input type="hidden" name="vendor_review_form_nonce" value="<?php echo wp_create_nonce('vendor_review_form_nonce'); ?>">
    <input type="submit" value="Submit">
</form>

</code></pre>
<!-- /wp:code -->

I have tried the above but all that happens is the page refreshes.


Solution

  • The issue is in your front-end form.

    You need to specify the <form> tags action attribute to be admin-post.php.

    <form action="<?php echo admin_url('admin-post.php'); ?>" method="post">