Sending a JSON response from WordPress with wp_send_json

The WordPress wp_send_json function is used to send a JSON response back to the client. This can be useful for sending data from the server to the client in a structured format, allowing for easy parsing and manipulation on the client side.

By using wp_send_json, developers can easily send complex data structures such as arrays or objects to the client, which can then be accessed and used in JavaScript code. This can be particularly useful for AJAX requests or for building single-page applications where data needs to be dynamically updated without requiring a full page reload.

wp_send_json provides a convenient way for WordPress developers to send JSON data from the server to the client, enabling rich and interactive user experiences on the web.

Parameters Accepted by wp_send_json Function

The wp_send_json function accepts the following parameters:

  • $response (mixed) – required. This is the variable, usually an array or object, that will be encoded as JSON, printed, and then the script will die.
  • $status_code (int) – optional. Default value is null. This parameter is used to specify the HTTP status code to be output.
  • $options (int) – optional. This parameter allows you to pass options to the json_encode() function. The default value is 0.

The function does not return a value.

Examples

How to send JSON response in WordPress

Example 1: Sending a simple JSON response

wp_send_json( array( 'message' => 'Hello, world!' ) );

This code snippet sends a simple JSON response with a message “Hello, world!”. The wp_send_json function takes an array as its parameter and sends it as a JSON response to the client.

Example 2: Sending a JSON response with HTTP status code

$data = array(
 'error' => true,
 'message' => 'Something went wrong'
);
wp_send_json( $data, 400 );

This code snippet sends a JSON response with an error message and sets the HTTP status code to 400. The wp_send_json function takes two parameters – the data to be sent as JSON and the HTTP status code.

Conclusion

In conclusion, the wp_send_json function is an essential feature for sending JSON responses in WordPress. It provides a simple and efficient way to communicate data between the server and the client, making it an essential function for developers working with WordPress. By using wp_send_json, developers can streamline their code and improve the overall performance of their applications. Additionally, the function’s built-in security features help to protect against potential vulnerabilities, ensuring that data is transmitted safely. Overall, wp_send_json is a valuable function that can greatly enhance the development process for WordPress projects.

Related WordPress Functions