wp_send_json() WordPress Function

The wp_send_json() function is used to send JSON data to the browser. It is similar to the wp_send_json_success() function, but it can also be used to send error messages.

wp_send_json( mixed $response, int $status_code = null, int $options ) #

Send a JSON response back to an Ajax request.


Parameters

$response

(mixed)(Required)Variable (usually an array or object) to encode as JSON, then print and die.

$status_code

(int)(Optional) The HTTP status code to output.

Default value: null

$options

(int)(Optional) Options to be passed to json_encode(). Default 0.


Top ↑

Source

File: wp-includes/functions.php

function wp_send_json( $response, $status_code = null, $options = 0 ) {
	if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: 1: WP_REST_Response, 2: WP_Error */
				__( 'Return a %1$s or %2$s object from your callback when using the REST API.' ),
				'WP_REST_Response',
				'WP_Error'
			),
			'5.5.0'
		);
	}

	if ( ! headers_sent() ) {
		header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
		if ( null !== $status_code ) {
			status_header( $status_code );
		}
	}

	echo wp_json_encode( $response, $options );

	if ( wp_doing_ajax() ) {
		wp_die(
			'',
			'',
			array(
				'response' => null,
			)
		);
	} else {
		die;
	}
}


Top ↑

Changelog

Changelog
VersionDescription
5.6.0The $options parameter was added.
4.7.0The $status_code parameter was added.
3.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More