wpseek.com
A WordPress-centric search engine for devs and theme authors



wp_send_json › WordPress Function

Since3.5.0
Deprecatedn/a
wp_send_json ( $response, $status_code = null, $flags = 0 )
Parameters: (3)
  • (mixed) $response Variable (usually an array or object) to encode as JSON, then print and die.
    Required: Yes
  • (int) $status_code Optional. The HTTP status code to output. Default null.
    Required: No
    Default: null
  • (int) $flags Optional. Options to be passed to json_encode(). Default 0.
    Required: No
    Default:
Defined at:
Codex:
Change Log:
  • 4.7.0
  • 5.6.0

Sends a JSON response back to an Ajax request.



Source

function wp_send_json( $response, $status_code = null, $flags = 0 ) {
	if ( wp_is_serving_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, $flags );

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