wp_send_json_error

Send a JSON response back to an Ajax request, indicating failure.

Description

wp_send_json_error( (null) $data = null ); 

If the $data parameter is a WP_Error object, the errors within the object are processed and output as an array of error codes and corresponding messages. All other types are output without further processing.

Parameters (1)

0. $data — Optional. (null) => null
Data to encode as JSON, then print and die.

Usage

  1. if ( !function_exists( 'wp_send_json_error' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // Data to encode as JSON, then print and die. 
  5. $data = null; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wp_send_json_error($data); 
  9.  

Defined (1)

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

/wp-includes/functions.php  
  1. function wp_send_json_error( $data = null ) { 
  2. $response = array( 'success' => false ); 
  3.  
  4. if ( isset( $data ) ) { 
  5. if ( is_wp_error( $data ) ) { 
  6. $result = array(); 
  7. foreach ( $data->errors as $code => $messages ) { 
  8. foreach ( $messages as $message ) { 
  9. $result[] = array( 'code' => $code, 'message' => $message ); 
  10.  
  11. $response['data'] = $result; 
  12. } else { 
  13. $response['data'] = $data; 
  14.  
  15. wp_send_json( $response );