Nonces are used to add an extra layer of security to WordPress. They are typically used when submitting form data to ensure that the form is being submitted from where it’s supposed to. Nonce fields help us protect our forms from malicious attacks and non-authorized submissions. This tutorial will introduce you to using nonces in your forms.

Here is the code written in the video:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// sample form with nonce
function pippin_sample_nonce_form() {
 
	ob_start(); ?>
 
		<form id="pippin_nonce_sample" method="POST" action="">
			<p>
				<input type="hidden" name="pippin_sample_nonce" value="<?php echo wp_create_nonce('pippin-sample-nonce'); ?>"/>
				<input type="submit" value="Submit"/>
			</p>
		</form>
		<?php
	return ob_get_clean();
}
add_shortcode('nonce_form', 'pippin_sample_nonce_form');
 
// processes the data submitted by the form
function pippin_process_form_data() {
 
	if(isset($_POST['pippin_sample_nonce'])) {
		if(wp_verify_nonce($_POST['pippin_sample_nonce'], 'pippin-sample-nonce')) {
 
			echo 'Nonce verified successfully'; exit;
			// process form here
 
		} else {
			echo 'nonce verification failed'; exit;
		}
	}
}
add_action('init', 'pippin_process_form_data');
You must be a premium subscriber to view the code written in the video
  1. surendra

    I am developing a plugin, where I am using bootstrap nav tabs function to display different forms on selecting menu . I want to use nonce function . Should I give seperate nonce function for every form or same nonce for all the forms as they are on the same page. Pls guide.?

    • Pippin

      One nonce per form.

Comments are closed.