wp_send_json_error

Home » Functions » wp_send_json_error

Function Name: wp_send_json_error

If you’re working on a WordPress project and need to send an error message back to the browser, you can use the "wp_send_json_error" function. This function returns a JSON object that contains an error message.

The "wp_send_json_error" function takes two parameters: $data and $status_code. The $data parameter is the error message that you want to send back to the browser, and the $status_code parameter is the HTTP status code that you want to return.

This function is often used by WordPress developers to handle errors and exceptions. For example, if a user tries to save a post but there is an error, you can use the "wp_send_json_error" function to send an error message back to the browser.

Here’s an example usage code:

function my_function() {
  $result = some_process();
  if ( is_wp_error( $result ) ) {
    wp_send_json_error( $result->get_error_message(), 400 );
  } else {
    wp_send_json_success( $result );
  }
}

In this code, the "my_function" function is processing some data, and if there is an error, it calls the "wp_send_json_error" function with the error message and a status code of 400 (Bad Request). If there is no error, it calls the "wp_send_json_success" function with the result.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.