How to handle form submission?

You should use the wp_ajax or the wp_ajax_nopriv function.

First of all you should put the the admin ajax url as the action attribute value in the submission form.

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

That way the the form will be submitted to the admin-ajax.php by default (without JavaScript). You can use JavaScript to make it work using AJAX.

Next is the function that will use the submitted data. Inside the form, put a wp_nonce_field and a hidden input with the name action. My action value is add_transfer.

<?php wp_nonce_field('add_transfer','security-code-here'); ?>
<input name="action" value="add_transfer" type="hidden">

You can put the function that will handle this form in the functions.php or in your plugin file. You can use wp_ajax_ + the action name if this is a form only for logged in users. For non logged in users, use wp_ajax_nopriv + the action name instead.

add_action('wp_ajax_add_transfer', 'process_add_transfer');

function process_add_transfer() {
    if ( empty($_POST) || !wp_verify_nonce($_POST['security-code-here'],'add_transfer') ) {
        echo 'You targeted the right function, but sorry, your nonce did not verify.';
        die();
    } else {
        // do your function here 
        wp_redirect($redirect_url_for_non_ajax_request);
    }
}

Leave a Comment