From 34bd90a7c9221f3c8e19668709ac9c9db5b6d274 Mon Sep 17 00:00:00 2001 From: Felix Arntz Date: Wed, 16 Jan 2019 15:21:49 +0000 Subject: [PATCH] Bootstrap/Load: Add support for JSON requests to `wp_die()`. In addition to AJAX and XML-RPC requests, `wp_die()` now handles JSON requests correctly, returning information in the expected content type. Props spacedmonkey. See #45933, #44458. git-svn-id: https://develop.svn.wordpress.org/trunk@44625 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/functions.php | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index 36b59ac8e1..ca91c53e00 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -2975,6 +2975,15 @@ function wp_die( $message = '', $title = '', $args = array() ) { * @param callable $function Callback function name. */ $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' ); + } elseif ( wp_is_json_request() ) { + /** + * Filters the callback for killing WordPress execution for JSON requests. + * + * @since 5.1.0 + * + * @param callable $function Callback function name. + */ + $function = apply_filters( 'wp_die_json_handler', '_json_wp_die_handler' ); } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) { /** * Filters the callback for killing WordPress execution for XML-RPC requests. @@ -3215,6 +3224,40 @@ function _default_wp_die_handler( $message, $title = '', $args = array() ) { die(); } +/** + * Kill WordPress execution and display JSON message with error message. + * + * This is the handler for wp_die when processing JSON requests. + * + * @since 5.1.0 + * @access private + * + * @param string $message Error message. + * @param string $title Optional. Error title. Default empty. + * @param string|array $args Optional. Arguments to control behavior. Default empty array. + */ +function _json_wp_die_handler( $message, $title = '', $args = array() ) { + $defaults = array( 'response' => 500 ); + + $r = wp_parse_args( $args, $defaults ); + + $data = array( + 'code' => 'wp_die', + 'message' => $message, + 'status' => $r['response'], + ); + + if ( ! headers_sent() ) { + header( 'Content-Type: application/json; charset=utf-8' ); + if ( null !== $r['response'] ) { + status_header( $r['response'] ); + } + } + + echo wp_json_encode( $data ); + die(); +} + /** * Kill WordPress execution and display XML message with error message. *