Skip to content

WordPress form submission the right way

Building a WordPress form can be a tricky way to do it, if you want to do it the right way. Done a little bit of study on the subject and found out what is seem to be the right way to handle form submission on wordpress, a quick how to explained below:

Form design requirements:

<form method='POST' action='<?php echo admin_url( 'admin-post.php' ); ?>'>
 <input type='text' value='field content value' name='field_name'/>
 <input type='hidden' name='action' value='submitform'/>
 <?php wp_nonce_field( 'submitform', 'submitform_nonce' ); ?>

<input type="submit" value="Send"/>
 </form>

One of the most used forms of WordPress has to perform a form request is using the admin-post.php endpoint. We define the action of the form for the /wp-admin/admin-post.php.

<form method=’POST’ action=’<?php echo admin_url( ‘admin-post.php’ ); ?>‘>

Them, we’d need to define what form action are we handling, this can be done by using the hidden field with name ‘action’

<input type=’hidden’ name=’action’ value=’submitform’/>

This will allow you to handle the form submission just after.

 

Now that you have build your form, you’d need to add the handling to your theme or plugin.

WordPress allows handling fo actions using the add_action function.

On your theme functions.php file or on your plugin initialization just add handling for this function.

add_action( ‘admin_post_nopriv_submitform’ : Triggered by wordpress upon form submission on non-authenticated users.

add_action( ‘admin_post_submitform’ : Triggered by wordpress upon form submission on authenticated users.

WordPress.org reference to both handling:

admin_post_nopriv_{$action}

admin_post_{$action}

If you have any doubt or need any help just comment on the post and i’ll get back to you.

Published inCodingphpwordpress

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *