0

I am learning WordPress coding. I have a Form like below.

<form action="" method="post" enctype="multipart/form-data">
    <input type="text" name="first_name" />
    <input type="text" name="last_name" />
    <input type="submit" value="Submit>
</form>

How can I catch submission of the Form in a file of WordPress ?

1
  • 1
    There are different hooks that you can choose from, e.g. admin_post_<action name> for logged-in users. You could also use the REST API, but as a starter, you can try the admin_post_ hook. Or on-same-page hook like template_redirect where conditional tags like is_page() would work correctly.
    – Sally CJ
    Jul 17, 2021 at 17:16

1 Answer 1

1

You have multiple way yo handle form submition, one of those is a post action.

But first you need to create the proper form attributes and tags for it to work, so it should look something like this.

HTML

<form action="<?= esc_url(admin_url('admin-post.php')); ?>" method="post">
    <!-- this will "indicte" to the hook that will handle the submition -->
    <input type="hidden" name="action" value="action_my_hook_name">
    <!-- if needed you can add a nonce for security -->
    <input type="hidden" name="security" value="<?= wp_create_nonce('my_form_nonce'); ?>">

    <input type="text" name="first_name" />
    <input type="text" name="last_name" />
    <input type="submit" value="Submit">
</form>

PHP (in functions.php)

add_action('admin_post_action_my_hook_name', 'action_my_hook_name'); // logged in users
add_action('admin_post_nopriv_action_my_hook_name', 'action_my_hook_name'); // not logged in users

function action_my_hook_name () {
    // checking if nonce was submited and is valid, if not valid will exit
    check_ajax_referer('bt_site_nonce', 'security');

    // handle form submition
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.