wp_nonce_field

Retrieve or display nonce hidden field for forms.

Description

(string) wp_nonce_field( (int) $action = -1, (string) $name = '_wpnonce', (bool) $referer = true, (bool) $echo = true ); 

The nonce field is used to validate that the contents of the form came from the location on the current site and not somewhere else. The nonce does not offer absolute protection, but should protect against most cases. It is very important to use nonce field in forms.

The $action and $name are optional, but if you want to have better security, it is strongly suggested to set those two parameters. It is easier to just call the function without any parameters, because validation of the nonce doesn't require any parameters, but since crackers know what the default is it won't be difficult for them to find a way around your nonce and cause damage.

The input name will be whatever $name value you gave. The input value will be the nonce creation value.

Returns (string)

Nonce field HTML markup.

Parameters (4)

0. $action — Optional. (int) => -1
Action name. Default -1.
1. $name — Optional. (string) => '_wpnonce'
Nonce name. Default _wpnonce..
2. $referer — Optional. (bool) => true
Whether to set the referer field for validation. Default true.
3. $echo — Optional. (bool) => true
Whether to display or return hidden form field. Default true.

Usage

  1. if ( !function_exists( 'wp_nonce_field' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // Optional. Action name. Default -1. 
  5. $action = -1; 
  6.  
  7. // Optional. Nonce name. Default '_wpnonce'. 
  8. $name = '_wpnonce'; 
  9.  
  10. // Optional. Whether to set the referer field for validation. Default true. 
  11. $referer = true; 
  12.  
  13. // Optional. Whether to display or return hidden form field. Default true. 
  14. $echo = true; 
  15.  
  16. // NOTICE! Understand what this does before running. 
  17. $result = wp_nonce_field($action, $name, $referer, $echo); 
  18.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.php  
  1. function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) { 
  2. $name = esc_attr( $name ); 
  3. $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />'; 
  4.  
  5. if ( $referer ) 
  6. $nonce_field .= wp_referer_field( false ); 
  7.  
  8. if ( $echo ) 
  9. echo $nonce_field; 
  10.  
  11. return $nonce_field;